Dictionaries are another mutable container model that can store objects of any type. The dictionary format is key-value.

5.1 Creating a Dictionary

>>> info = {}
>>> info = dict()
Copy the code

5.2 Initializing the Dictionary

>>> info = {"only_one" : 'python'} >>> info = dict(only_one= 'python') # 更 elegant The second way seems more reasonable, but causes unnecessary bugs >>> key = 'python' >>> info = {key, : 'best!! '} >>> info = {key : 'best!! '} >>> info {'python': 'best!! '} >>> info = dict(key = 'best!! ') >>> info {'key': 'best!! '} Python dictionaries have another way of initializing them, which is to use the dictionary's fromkeys method to get an element from a list as a key and initialize >>> info = {}. Fromkeys (['name', 'python']) >>> info {'blog': None, 'name': None} >>> info = dict().fromkeys(['name', 'blog']) >>> info {'blog': None, 'name': None} >>> info = dict().fromkeys(['name', 'blog'], 'linuxzen.com') >>> info {'blog': 'linuxzen.com', 'name': 'linuxzen.com'}Copy the code

5.3 Basic Operations of dictionaries

The basic behavior of dictionaries is similar to sequences in many ways.

  • Len (d) returns the number of items (key  value pairs) that dictionary d contains.
  • D [k] returns the value associated with the key k.
  • D [k] = v associates the value v with the key k.
  • Del d[k] Deletes the item whose key is K.
  • K in d Checks whether dictionary D contains items with key K.

While dictionaries and lists have more than one thing in common, they also have some important differences.

  • Key types: Keys in dictionaries can be integers, but they do not have to be. Keys in dictionaries can be any immutable type, such as floating point numbers (real numbers), strings, or tuples.
  • Auto add: You can assign a value to a key that does not already exist in the dictionary, which creates a new item in the dictionary. However, you cannot assign values to elements that are not in the list without using append or other similar methods.
  • Membership: ** The expression key in dict (where dict is a dictionary) looks for keys instead of values, and the expression value in list (where L is a list) looks for values instead of indexes. ** This may seem inconsistent, but once you get used to it, it will feel quite natural. After all, if the dictionary contains the specified key, it’s easy to check the corresponding value.

5.4 Dictionary method

  • clear()

The clear method removes all dictionary entries, which is done in-place (just like list.sort) and therefore returns nothing (or None).

>>> x = {} >>> y = x >>> x['key'] = 'shu' >>> x {'key': 'shu'} >>> y {'key': 'shu'} >>> x.clear() >>> x {} >>> y {} # ------------------------------------------------------------------------------------------------------------- >>> a = {}  >>> b = a >>> a['key-1'] = 'qiang' >>> a {'key-1': 'qiang'} >>> b {'key-1': 'qiang'} > > > a = {} > > > a {} > > > b {' key - 1 ':' qiang '} # the scene a and b point to the same dictionary, this time just a = {}, does not affect the value of b.Copy the code
  • Copy () Copy () is a shallow copy. The following example shows that directly modifying the data of the copy causes the value of the original data to change.
>>> x = {'name':'xuxing', 'body-info':['175', '65', '25']}         
>>> x
{'name': 'xuxing', 'body-info': ['175', '65', '25']}
>>> y = x.copy()
>>> y
{'name': 'xuxing', 'body-info': ['175', '65', '25']}
>>> y['name'] = 'niudun'
>>> x
{'name': 'xuxing', 'body-info': ['175', '65', '25']}
>>> y
{'name': 'niudun', 'body-info': ['175', '65', '25']}
>>> 
>>> y['body-info'].remove('65')      
>>> 
>>> x
{'name': 'xuxing', 'body-info': ['175', '25']}
>>> y
{'name': 'niudun', 'body-info': ['175', '25']}
>>> 
Copy the code

Deep copy deepcopy ()

>>> from copy import deepcopy
>>> 
>>> x = {'name':'xuxing', 'body-info':['175', '65', '25']}  
>>> y = x.copy()
>>> z = deepcopy(y)
>>> x['body-info'].append('500') 
>>> x
{'name': 'xuxing', 'body-info': ['175', '65', '25',, '500']}
>>> y
{'name': 'xuxing', 'body-info': ['175', '65', '25', '500']}
>>> z
{'name': 'xuxing', 'body-info': ['175', '65', '25']}
>>> 
Copy the code
  • Fromkeys () fromkeys creates a new dictionary that contains the specified keys, and defaults to None for each key, which can be customized.
>>> {}.fromkeys(['name', 'age'])   
{'name': None, 'age': None}
>>> dict.fromkeys(['name', 'age'])
{'name': None, 'age': None}
>>> dict.fromkeys(['name', 'age'], 'nice-value')             
{'name': 'nice-value', 'age': 'nice-value'}
>>> 
Copy the code
  • Get () dict.get(key, default=None) returns the value of the specified key, or default if the value is not in the dictionary
  • Has_key () dict.has_key(key) returns true if the key is in the dict, false otherwise
  • Items () dict.items() returns a traversable array of (key, value) tuples as a list
  • Pop () pop(key[,default]) deletes the value corresponding to the given key in the dictionary, and returns the deleted value. The key value must be given. Otherwise, the default value is returned.
  • Popitem () returns and deletes a random pair of keys and values from the dictionary.
  • Dict. update(dict2) Updates the dictionary dict2 key/value pair to the dict.