A dictionary is the only built-in ing type in python. The values in the dictionary have no special order, but they are all stored in a specific key. A dictionary is the only built-in ing type in python. The values in the dictionary have no special order, but they are all stored in a specific key.
Keys can be numbers, strings, or even tuples.
1. create and use dictionaries
You can create a dictionary as follows:
The code is as follows:
Phonebook = {'Alice ': '000000', 'Beth': '000000', 'ceil ': '000000 '}
A dictionary consists of multiple keys and their corresponding values. Each key and its value are separated by a colon (:), and items are separated by commas (,). the entire dictionary is enclosed by a pair of braces. Empty Dictionary :{}
1.1 dict functions
You can use dict functions to create a dictionary through ing (such as other dictionaries) or sequences such as keys and values.
The code is as follows:
>>> Items = [('name', 'Gumby'), ('age'. 42)]
>>> D = dict (items)
>>> D
{'Age': 42, 'name': 'Gumby '}
>>> D = dict (name = 'Gumby', 'age' = 42)
>>> D
{'Age': 42, 'name': 'Gumby '}
1.2 Basic dictionary operations
(1) len (d) returns the number of key-value pairs in d;
(2) d [k] returns the value associated with k;
(3) d [k] = v associates the value v with the key k;
(4) del d [k] delete the key k;
(5) k in d check whether there are items with k keys in d;
1.3 formatted string of the dictionary
Dictionary formatting string: After % characters in each conversion specifier, you can add a (enclosed in parentheses) key, followed by other explanatory elements.
As long as all given keys can be found in the dictionary, you can get any number of conversion specifiers.
The code is as follows:
>>> Temple = 'The price of cake is $ % (cake) s, the price of milk of cake is $ % (milk) s. $ % (cake) s is OK'
>>> Price = {'cake': 4, 'milk': 5}
>>> Print temple % price
'The price of cake is $4, the price of milk of cake is $5. $4 is OK'
1.4 Dictionary method
1.4.1 clear
The clear method clears all the items in the dictionary. this is an in-situ operation and has no return value (or returns none ).
Consider the following two cases:
A. associate x with a new empty dictionary to clear it. this has no effect on y, and y is associated with the original dictionary.
The code is as follows:
>>> X = {}
>>> Y = x
>>> X ['key'] = 'value'
>>> Y
{'Key': 'value '}
>>> X = {}
>>> Y
{'Key': 'value '}
B. to clear all the elements in the original dictionary, use the clear method.
The code is as follows:
>>> X = {}
>>> Y = x
>>> X ['key'] = 'value'
>>> Y
{'Key': 'value '}
>>> X. clear ()
>>> Y
{}
1.4.2 copy
The copy method returns a new dictionary with the same key-value pairs (this method implements shortest replication, because the values are the same, not copies)
The original dictionary is not affected when values are replaced in the replicas. However, if a value is modified, the original dictionary changes.]
The code is as follows:
>>> X = {'a': 1, 'B': [2, 3, 4]}
>>> Y = x. copy ()
>>> Y ['A'] = 5
>>> Y ['B']. remove (3)
>>> Y
{'A': 5, 'B': [2, 4]}
>>> X
{'A': 1, 'B': [2, 4]}
To avoid this problem, you can use deep copy-deepcopy () to copy all the values.
The code is as follows:
>>> X = {'a': 1, 'B': [2, 3, 4]}
>>> Y = x. copy ()
>>> Z = x. deepcopy ()
>>> X ['A']. append (5)
>>> Y
{'A': 3.4, 'B': [2,]}
>>> Z
{'A': 1, 'B': [2, 3, 4]}
1.4.3 fromkeys
The fromkeys method uses the given key to create a new dictionary. the default value of each key is None. you can call this method directly on dict of all dictionary types. If you do not want to use the default value, you can also provide your own value.
The code is as follows:
>>>{}. Fromkeys (['name', 'age'])
{'Age': None, 'name': None}
>>>
>>> Dict. fromkeys (['name', 'age'], 'unknow ')
{'Age': 'unknow', 'name': 'unknow '}
1.4.4 get
The get method is a more loose method for accessing dictionary items. When you use get to access a key that does not exist, the value of None is obtained. You can also customize the "default" value to replace None.
The code is as follows:
>>> D = {}
>>> Print d. get ('name ')
None
>>> D. get ("name", 'n'/')
'N'/'
>>> D [''name] = 'Eric'
>>> D. get ('name ')
'Eric'
1.4.5 has_key
The has_key method can check whether the dictionary contains the given key. D. has_key (k)
The code is as follows:
>>> D = {}
>>> D. has_key ('name ')
False
1.4.6 items and iteritems
The items method returns all Dictionary items in the list, but each item (key, value) in the list has no special order. The iteritems method works roughly the same but returns an iterator object instead of a list:
The code is as follows:
>>> D = {'a': 1, 'B': 2, 'C': 3}
>>> D. items
[('A', 1), ('B', 2), ('C', 3)]
>>> It = d. iteritems ()
>>> It
>>> List (it)
[('A', 1), ('B', 2), ('C', 3)]
1.4.7 keys and iterkeys
The keys method returns keys in the dictionary in the form of a list, while the iterkeys method returns the iterator for keys.
1.4.8 pop method
The pop method is used to obtain the value of the corresponding key, and then remove the key-value pair from the dictionary.
The code is as follows:
>>> D = {'a': 1, 'B': 2, 'C': 3}
>>> D. pop ('A ')
>>> D
{'B': 2, 'C': 3}
1.4.10 setdefault
To some extent, the setdefault method is similar to the get method, that is, it can obtain the value associated with the given key, and set the corresponding key value without a given key in the dictionary.
The code is as follows:
>>> D = {}
>>> D. setdefault ('name', 'n'/')
'N'/'
>>> D
{'Name': 'N'/'}
>>> D. setdefault ('name',)
'N'/'
In the preceding example, when a key exists, the default value (optional) is returned and the dictionary is updated accordingly. if the key exists, the corresponding value is returned without changing the dictionary.
1.4.11 update
The update method can use one dictionary item to update another dictionary. The provided dictionary items are added to the old dictionary. if they have the same key, they are overwritten.
The code is as follows:
>>> D = {'a': 1, 'B': 2, 'C': 3}
>>> X = {'a': 5, 'D': 6}
>>> D. update (x)
>>> D
{'A': 5, 'C': 3, 'B': 2, 'D': 6}
1.4.12 values and itervalues
The values method returns the value in the dictionary in the form of a list (itervalues return value iterator). Unlike the return key list, the return value list can contain repeated elements.
The code is as follows:
>>> D = {}
>>> D [1] = 1
>>> D [2] = 2
>>> D [3] = 3
>>> D [4] = 1
>>> D
{1: 1, 2: 2, 3: 3, 4: 1}
>>> D. values ()
[1, 2, 3, 1]