[Python] detailed explanation, addition, deletion and modification of dict dictionary

summary

Python Dictionary (dict) is an unordered and variable sequence. Its elements are stored in the form of "key value". In contrast, list s and tuple s are ordered sequences, and their elements are stored next to each other at the bottom.

The dictionary type is the only mapping type in Python.

"Mapping" is a term in mathematics. It refers to the corresponding relationship between elements, that is, one element can uniquely find another element.

In the dictionary, it is customary to refer to the index corresponding to each element as a key, the element corresponding to each key as a value, and the key and its associated value as a "key value pair".

The dictionary type is very similar to Xinhua dictionary.

We know that we can quickly find the Chinese characters we want to find through the syllable table in Xinhua dictionary. Among them, the syllable table in the dictionary is equivalent to the key in the dictionary type, and the Chinese character corresponding to the key is equivalent to the value.

In general, the main characteristics of dictionary types are as follows.

Main featuresexplain
Elements are read by keys rather than by indexesDictionary types are sometimes referred to as associative arrays or hash tables. It links a series of values through keys, so that the specified item can be obtained from the dictionary through keys, but not through indexes.
A dictionary is an unordered collection of arbitrary data typesUnlike lists and tuples, the element corresponding to index value 0 is usually called the first element, while the elements in the dictionary are unordered.
Dictionaries are mutable and can be nested arbitrarilyThe dictionary can grow or shorten in place (without generating a copy), and it supports nesting at any depth, that is, the values stored in the dictionary can also be lists or other dictionaries.
Keys in the dictionary must be uniqueThe dictionary does not support multiple occurrences of the same key, otherwise only the last key value pair will be retained.
Keys in the dictionary must be immutableThe key of each key value pair in the dictionary is immutable. You can only use numbers, strings or tuples, not lists.

The dictionary type in Python is equivalent to the Map object in Java or C + +.

Like lists and tuples, dictionaries have their own types. In Python, the data type of the dictionary is dict, which can be viewed through the type() function:

>>> a = {'one': 1, 'two': 2, 'three': 3}  #A is a dictionary type
>>> type(a)
<class 'dict'>

Create Dictionary (3 ways)

Create dictionary using {}

Since each element in the dictionary contains two parts, namely key and value, when creating a dictionary, keys and values are separated by colons, and adjacent elements are separated by commas. All elements are placed in braces {}.

The syntax format for creating a dictionary using {} is as follows:

dictname = {'key':'value1', 'key2':'value2', ..., 'keyn':valuen}

Where dictname represents the dictionary variable name, and key: valuen represents the key value pair of each element. It should be noted that each key in the same dictionary must be unique and cannot be repeated.

#Use string as key
scores = {'mathematics': 95, 'English': 92, 'language': 84}
print(scores)
Output:{'mathematics': 95, 'English': 92, 'language': 84}

#Use tuples and numbers as key s
dict1 = {(20, 30): 'great', 30: [1,2,3]}
print(dict1)
Output:{(20, 30): 'great', 30: [1, 2, 3]}

#Create empty tuple
dict2 = {}
print(dict2)
Output:{}

It can be seen that the key of the dictionary can be integer, string or tuple, as long as it conforms to the unique and immutable characteristics; The value of the dictionary can be any data type supported by Python.

Create a dictionary through the fromkeys() method

In Python, you can also use the fromkeys() method provided by dict dictionary type to create a dictionary with default values. The specific format is:

dictname = dict.fromkeys(list,value=None)

The list parameter represents the list of all keys in the dictionary; The value parameter represents the default value. If it is not written, it is null None.

Take the following example:

knowledge = ['language', 'mathematics', 'English']
scores = dict.fromkeys(knowledge, 60)
print(scores)

Output:{'language': 60, 'English': 60, 'mathematics': 60}

You can see that all the elements in the knowledge list are used as the keys of the scores dictionary, and the corresponding value of each key is 60.

This creation method is usually used to initialize the dictionary and set the default value of value.

Create a dictionary through the dict() mapping function

a = dict(str1=value1, str2=value2, str3=value3)

str represents the key of string type, and value represents the value corresponding to the key. When creating a dictionary in this way, strings cannot be quoted.


#Mode 1
demo = [('two',2), ('one',1), ('three',3)]
#Mode 2
demo = [['two',2], ['one',1], ['three',3]]
#Mode 3
demo = (('two',2), ('one',1), ('three',3))
#Mode 4
demo = (['two',2], ['one',1], ['three',3])
a = dict(demo)

Pass in a list or tuple to the dict() function, and the elements in them are lists or tuples containing two elements, with the first element as the key and the second element as the value.


keys = ['one', 'two', 'three'] #It can also be a string or tuple
values = [1, 2, 3] #It can also be a string or tuple
a = dict( zip(keys, values) )

Note that no matter which of the above methods is used to create a dictionary, the key of each element in the dictionary can only be a string, tuple or number, not a list. The list is mutable and cannot be used as a key.

If no parameters are passed in for the dict() function, an empty dictionary is created, for example:

# Create an empty dictionary
d = dict()
print(d)
Output:{}

ACCESS Dictionary

Unlike lists and tuples, which access elements through subscripts, dictionaries access corresponding values through keys.

Because the elements in the dictionary are out of order and the position of each element is not fixed, the dictionary can not access multiple elements at one time by slicing like lists and tuples.

The specific format of Python ACCESS Dictionary elements is:

dictname[key]

Where dictname represents the name of the dictionary variable and key represents the key name. Note that the key must exist or an exception will be thrown.

Take the following example:

tup = (['two',26], ['one',88], ['three',100], ['four',-59])
dic = dict(tup)
print(dic['one'])  #Key exists
print(dic['five'])  #Key does not exist
 Output:
88
Traceback (most recent call last):
    File "C:\Users\qinjl\Desktop\demo.py", line 4, in <module>
        print(dic['five'])  #Key does not exist
KeyError: 'five'

In addition to the above method, Python recommends using the get() method provided by dict type to obtain the value corresponding to the specified key. The get() method does not throw an exception when the specified key does not exist.

The syntax format of get() method is:

dictname.get(key[,default])

Where dictname represents the name of the dictionary variable; Key indicates the specified key; Default is used to specify the default value returned by this method when the key to query does not exist. If it is not specified manually, it will return None.

a = dict(two=0.65, one=88, three=100, four=-59)
print( a.get('one') )
Output: 88

Note that when the key does not exist, get() returns a null value of None. If you want to explicitly prompt the user that the key does not exist, you can manually set the second parameter of get(), for example:

a = dict(two=0.65, one=88, three=100, four=-59)
print( a.get('five', 'The key does not exist') )
Output: the key does not exist

Delete dictionary

Like deleting lists and tuples, you can also use del keyword to manually delete dictionaries, for example:

a = dict(two=0.65, one=88, three=100, four=-59)
print(a)
del a
print(a)
Output:
{'two': 0.65, 'one': 88, 'three': 100, 'four': -59}
Traceback (most recent call last):
    File "C:\Users\qinjl\Desktop\demo.py", line 4, in <module>
        print(a)
NameError: name 'a' is not defined

Basic operation of dict dictionary

Because the dictionary is a variable sequence, we can operate the key value pairs in the dictionary at will. In Python, there are several common dictionary operations:

  • Adds a new key value pair to an existing dictionary.

  • Modify key value pairs in an existing dictionary.

  • Deletes the specified key value pair from the existing dictionary.

  • Determines whether the specified key value pair exists in the existing dictionary.

Adding key value pairs to a dictionary

Adding a new key value pair to the dictionary is very simple. You can directly assign a value to a nonexistent key. The specific syntax format is as follows:

dictname[key] = value

The following code demonstrates the process of adding a new element based on an existing dictionary:

a = {'mathematics':95}
print(a)
Output:{'mathematics': 95}

#Add a new key value pair
a['language'] = 89
print(a)
Output:{'mathematics': 95, 'language': 89}

#Add a new key value pair again
a['English'] = 90
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90}

Dictionary modification key value pair

The name of the key in the Python dictionary cannot be modified. We can only modify the value.

The key of each element in the dictionary must be unique. Therefore, if the key of the newly added element is the same as that of the existing element, the value corresponding to the key will be replaced by the new value, so as to modify the element value. See the following code:

a = {'mathematics': 95, 'language': 89, 'English': 90}
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90}

a['language'] = 100
print(a)
Output:{'mathematics': 95, 'language': 100, 'English': 90}

It can be seen that instead of adding a {'language': 100} key value pair to the dictionary, the value in the original key value pair {language ': 89} has been modified.

Dictionary delete key value pair

If you want to delete key value pairs from the dictionary, you can still use the del statement. For example:

# Delete key value pairs using del statements
a = {'mathematics': 95, 'language': 89, 'English': 90}
del a['language']
del a['mathematics']
print(a)

Output:{'English': 90}

Determines whether the specified key value pair exists in the dictionary

If you want to judge whether there is a specified key value pair in the dictionary, you should first judge whether there is a corresponding key in the dictionary.

To determine whether the dictionary contains the key of the specified key value pair, you can use the in or not in operator.

It should be noted that for dict, the in or not in operators are judged based on the key.

a = {'mathematics': 95, 'language': 89, 'English': 90}
# Judge whether a contains a key named 'Math'
print('mathematics' in a) # True

# Judge whether a contains a key named 'physical'
print('Physics' in a) # False

Through the in (or not in) operator, we can easily judge whether the dictionary contains a key. If so, because the corresponding value can be easily obtained through the key, we can easily judge whether there is a specified key value pair in the dictionary.

dict dictionary method

The data type of Python dictionary is dict. We can use dir(dict) to see which methods this type contains, for example:

>>> dir(dict)
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

keys(), values(), items() methods

These three methods are introduced together because they are used to obtain specific data in the dictionary:

  • The keys() method is used to return all keys in the dictionary;

  • The values() method is used to return the values corresponding to all keys in the dictionary;

  • items() is used to return all key value pairs in the dictionary.

Take the following example:

scores = {'mathematics': 95, 'language': 89, 'English': 90}
print(scores.keys())
print(scores.values())
print(scores.items())

Output:
dict_keys(['mathematics', 'language', 'English'])
dict_values([95, 89, 90])
dict_items([('mathematics', 95), ('language', 89), ('English', 90)])

It can be found that the types of returned values of keys(), values(), and items() are dict respectively_ keys,dict_values ,dict_items.

In Python 3 If you want to use the data returned by these three methods in X, there are generally the following two schemes:

1. Use the list() function to convert the data returned by them into a list, for example:

a = {'mathematics': 95, 'language': 89, 'English': 90}
print(list(a.keys()))
print(list(a.values()))
print(list(a.items()))
Output:
['mathematics', 'language', 'English']
[95, 89, 90]
[('mathematics', 95), ('language', 89), ('English', 90)]

2. Use the for in loop to iterate over their return values, for example:

a = {'mathematics': 95, 'language': 89, 'English': 90}
for k in a.keys():
    print(k, end=' ')
print("\n---------------")
for v in a.values():
    print(v, end=' ')
print("\n---------------")
for k, v in a.items():
    print("key:", k, " value:", v)

Output:
Mathematics, Chinese and English
---------------
95 89 90
---------------
key: mathematics  value: 95
key: language  value: 89
key: English  value: 90

copy() method

The copy() method returns a copy of the dictionary, that is, a new dictionary with the same key value pair, for example:

a = {'one': 1, 'two': 2, 'three': [1,2,3]}
b = a.copy()
print(b)

Output:{'one': 1, 'two': 2, 'three': [1, 2, 3]}

Note that the copy() method follows both deep and shallow copy principles.

Take copy dictionary a as an example. The copy() method will only make a deep copy of the key value pairs at the outermost layer, that is, it will apply for another piece of memory to store {one ': 1,' two ': 2,' three ': []};

For some list type values, this method makes a shallow copy, that is, the values of [1,2,3] in b are not unique to themselves, but shared with a.

Take the following example:

a = {'one': 1, 'two': 2, 'three': [1,2,3]}
b = a.copy()
#Add a new key value pair to A. since b has copied all the key value pairs of a in advance, adding a new key value pair to a will not affect b.
a['four']=100
print(a)
print(b)
Output:
{'one': 1, 'two': 2, 'three': [1, 2, 3], 'four': 100}
{'one': 1, 'two': 2, 'three': [1, 2, 3]}

#Since b and a share [1,2,3] (shallow copy), removing the elements in the list in a will also affect b.
a['three'].remove(1)
print(a)
print(b)
Output:
{'one': 1, 'two': 2, 'three': [2, 3], 'four': 100}
{'one': 1, 'two': 2, 'three': [2, 3]}

It is not difficult to see from the running results that a new key value pair is added to a and b remains unchanged; If a modifies the elements in the list of a key value pair, b will change accordingly.

update() method

The update() method can use the key value pairs contained in a dictionary to update the existing dictionary.

When the update() method is executed, if the updated dictionary already contains the corresponding key value pair, the original value will be overwritten; If the updated dictionary does not contain the corresponding key value pair, the key value pair is added (if the key exists, the value is updated; if the key does not exist, the key value is added).

See the following code:

a = {'one': 1, 'two': 2, 'three': 3}
a.update({'one':4.5, 'four': 9.3})
print(a)
Output:{'one': 4.5, 'two': 2, 'three': 3, 'four': 9.3}

It can be seen from the running results that since the updated dictionary already contains the key value pair with key "one", the value of the key value pair will be overwritten when updating;

The updated dictionary does not contain a key value pair with a key of "four", so a new key value pair will be added to the original dictionary during update.

pop() and popitem() methods

Both pop() and popitem() are used to delete key value pairs in the dictionary. The difference is that pop() is used to delete specified key value pairs, while popitem() is used to randomly delete a key value pair. Their syntax format is as follows:

dictname.pop(key)
dictname.popitem()

Where dictname represents the dictionary name and key represents the key.

The following code demonstrates the usage of two functions:

a = {'mathematics': 95, 'language': 89, 'English': 90, 'Chemistry': 83, 'biology': 98, 'Physics': 89}
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90, 'Chemistry': 83, 'biology': 98, 'Physics': 89}

a.pop('Chemistry')
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90, 'biology': 98, 'Physics': 89}

a.popitem()
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90, 'biology': 98}

In fact, the description of popitem(), it is inaccurate to say that popitem() randomly deletes a key value pair in the dictionary. Although the dictionary is an unnecessary list, the key value pairs are also stored in the bottom layer. Popitem() always pops up the last key value in the bottom layer, which is similar to the pop() method of the list, and implements the "stack out" operation in the data structure.

setdefault() method

The setdefault() method is used to return the value corresponding to a key. Its syntax format is as follows:

dictname.setdefault(key, defaultvalue)

Note: dictname represents the dictionary name, key represents the key, and defaultvalue represents the default value (it can be left blank. If it is not written, it is None).

When the specified key does not exist, setdefault() will first set a default value for the non-existent key, and then return the default value (when the key exists, the corresponding value is returned; when the key does not exist, the default value is returned).

That is, the setdefault() method always returns the value corresponding to the specified key:

  • If the key exists, the value corresponding to the key will be returned directly (the value will not be updated);

  • If the key does not exist, set the default value for the key first, and then return the default value corresponding to the key.

See the following code:

a = {'mathematics': 95, 'language': 89, 'English': 90}
print(a)
Output:{'mathematics': 95, 'language': 89, 'English': 90}

#key exists. Specify the default value
value = a.setdefault('mathematics', 100)
print(value)
print(a)
Output:
95
{'mathematics': 95, 'language': 89, 'English': 90}

#key does not exist. Specify the default value
value = a.setdefault('Physics', 94)
print(a)
print(value)
Output:
94
{'mathematics': 95, 'language': 89, 'English': 90, 'Physics': 94}

#key does not exist. No default value is specified
a.setdefault('Chemistry')
print(a)
Output:
{'mathematics': 95, 'language': 89, 'English': 90, 'Physics': 94, 'Chemistry': None}


Keywords: Python Programming data structure map

Added by paulnaj on Mon, 17 Jan 2022 08:25:12 +0200