Dictionary is the only mapping type in Python language, represented by curly braces {}. A dictionary entry is a key-value pair. The method keys() returns the dictionary's key list, values() returns the dictionary's value list, and items() returns the dictionary's key-value pair list. There is no limit to the values in the dictionary. They can be any python object, but the keys in the dictionary have type restrictions. Each key can only correspond to one value, and the key must be halo-based, and all immutable types are hashable. The elements of the immutable set frozenset can be used as keys to the dictionary, but the variable set set cannot.
The following are common methods for dictionary types.
clear(): Delete all elements in the dictionary.
copy(): Returns a copy of the dictionary (shallow copy).
fromkeys(seq,val=None): Create and return a new dictionary, use the elements in seq as the keys of the dictionary, and val as the initial value corresponding to all keys in the dictionary.
get(key,default=None): Returns the value corresponding to the key key in the dictionary. If this key does not exist in the dictionary, the value of default is returned.
has_key(key): Returns True if the key key exists in the dictionary, otherwise returns False. After python2.2, this method is almost abandoned and is usually replaced by in.
items(): Returns a list of tuples of key-value pairs in the dictionary.
keys(): Returns a list containing keys in the dictionary.
iter(): The methods iteritems(), iterkeys(), and itervalues() are the same as their corresponding non-iterative methods, the difference is that they return an iterator instead of a list.
pop(key[,default]): Similar to method get(), if the key key exists in the dictionary, delete and return dict[key]. If the key key does not exist and the default value is not given, a KeyError exception is raised.
setdefault(key,default=None): Similar to the method get(). If there is no key in the dictionary, dict[key]=default will assign it a value.
update(dict2): Add the key-value pair of dictionary dict2 to the current dictionary.
values(): Returns a list containing all values in the dictionary.
Keys can be of multiple types, but keys are unique and non-repeatable. Values can be not unique.
>>> d = {'a':1, 'b':2} >>> d {'b': 2, 'a': 1} >>> L = [('Jonh',18), ('Nancy',19)] >>> d = dict(L) #Create through a list containing key values>>> d {'Jonh': 18, 'Nancy': 19} >>> T = tuple(L) >>> T (('Jonh', 18), ('Nancy', 19)) >>> d = dict(T) #Create from a tuple containing key values>>> d {'Jonh': 18, 'Nancy': 19} >>> d = dict(x = 1, y = 3) #Create through keyword parameters>>> d {'x': 1, 'y': 3} >>> d[3] = 'z' >>> d {3: 'z', 'x': 1, 'y': 3}
Another way to create a dictionary is fromkeys(S [ , v]) The explanation in python is New dict with key from S and value equal to v , that is, the elements in S are used as keys and v is used as the values of all keys, and the default value of v is None. It can be called by the existing dictionary d (S [, v] ) or by the type (S [, v] )
>>> d {3: 'z', 'y': 3} >>> L1 = [1,2,3] >>> (L1) {1: None, 2: None, 3: None} >>> {}.fromkeys(L1,'nothing') {1: 'nothing', 2: 'nothing', 3: 'nothing'} >>> (L1,'over') {1: 'over', 2: 'over', 3: 'over'}
The dictionary is unordered, so the value cannot be obtained through the index, and the associated value must be found through the key. For non-existent keys, an error KeyError will appear
>>> d {3: 'z', 'x': 1, 'y': 3} >>> d[3] 'z' >>> d['x'] 1 >>> d[0] Traceback (most recent call last): File "<pyshell#26>", line 1, in <module> d[0] KeyError: 0
Dictionary operations and methods:
len(d ) Returns the number of key-value pairs in dictionary d
x in d Query whether there is a key in the dictionary d
>>> d = {'x':1,'y':3} >>> len(d) 2 >>> 'x' in d True >>> 'z' not in d True
d [ x ] = y If the key x exists, modify the value corresponding to x to be y. If the key x does not exist, add the key-value pair x to the dictionary d: y
>>> d {'x': 1, 'y': 3} >>> d['x'] = 1.5 >>> d {'x': 1.5, 'y': 3} >>> d['z'] = 5 >>> d {'z': 5, 'x': 1.5, 'y': 3}
del d[x] Delete the key-value pair with the middle key of x in the dictionary d. If x does not exist, KeyError will appear
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> del d['x'] >>> d {'z': 5, 'y': 3} >>> del d['x'] Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> del d['x'] KeyError: 'x'
() Clear dictionary d
() Make a shallow copy of dictionary d and return a new dictionary with the same key-value pair as d
>>> d {'z': 5, 'y': 3} >>> () {'z': 5, 'y': 3}
( x [ , y]) Returns the value corresponding to the middle key x in the dictionary d. When the key x does not exist, it returns y. The default value of y is None
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> ('x') 1.5 >>> del d['x'] >>> ('x') >>> ('x','nothing') 'nothing'
() Return all key-value pairs in dictionary d as dict_items (Python 2 () returns an iterator object for key-value pairs, and there is no iteritems method in Python 3)
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> () dict_items([('z', 5), ('x', 1.5), ('y', 3)]) >>> list(()) [('z', 5), ('x', 1.5), ('y', 3)]
() Return all keys in dictionary d as dict_keys (Python 2 () returns an iterator object for keys, Python 3 does not have this syntax)
>>> () dict_keys(['z', 'x', 'y']) >>> for x in (): print(x) z x y
(x) Returns the value corresponding to the given key x and removes the key-value pair from the dictionary
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> ('x') 1.5 >>> ('x') Traceback (most recent call last): File "<pyshell#92>", line 1, in <module> ('x') KeyError: 'x'
( ) Return and delete random key-value pairs in dictionary d
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> () ('z', 5) >>> () ('x', 1.5)
( x, [ , y ] ) Returns the value corresponding to the key x in the dictionary d. If the key x does not exist, it returns y and add x : y as a key-value pair to the dictionary. The default value of y is None
>>> d = {'z': 5, 'x': 1.5, 'y': 3} >>> ('x') 1.5 >>> del d['x'] >>> ('x','Look!') 'Look!' >>> d {'z': 5, 'x': 'Look!', 'y': 3}
( x ) Add all key-value pairs of dictionary x to dictionary d (no duplicate, repetitive key-value pairs use key-value pairs in dictionary x instead of dictionary d)
>>> d1 = {'x':1, 'y':3} >>> d2 = {'x':2, 'z':1.4} >>> (d2) >>> d1 {'z': 1.4, 'x': 2, 'y': 3}
( ) Return all values in the dictionary as dict_values (Python 2 () returns an iterator object for all values in dictionary d, Python 3 does not have this syntax)
>>> d1 {'z': 1.4, 'x': 2, 'y': 3} >>> () dict_values([1.4, 2, 3]) >>> list(()) [1.4, 2, 3]