Python creates and USES dictionary instance details

  • 2020-04-02 13:14:26
  • OfStack

Dictionaries are the only built-in mapping type in python. The values in the dictionary are not in a particular order, but are stored in a particular key.
Keys can be Numbers, strings, or even tuples.
1. Create and use a dictionary
Dictionaries can be created by:

phonebook = {'Alice':'2341','Beth':'9102','Ceil':'3258'}

A dictionary consists of pairs of keys and their corresponding values. Each key is separated from its value by a colon (:), items by a comma (,), and the entire dictionary is enclosed in braces. Empty dictionary: {}

1.1 dict function
The dict function can be used to create dictionaries by mapping (such as other dictionaries) or sequences (keys, values).

>>> 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 operation
(1) len(d) returns the number of items (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 item whose key is k;
(5) k in d checks whether there is any term with the key of k in d;

1.3 the formatted string of the dictionary
Dictionary format string: after the % character in each conversion descriptor, you can add a key (enclosed in parentheses) followed by other explanation elements.
Any number of conversion specifiers can be obtained as long as all the keys given are found in the dictionary.

>>> 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 the clear
The clear method clears all entries in the dictionary. This is a in situ operation that returns no value (or none).
Consider the following two scenarios:
A. Associating x with a new empty dictionary to empty it has no effect on y, which is still related to the original dictionary

>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key':'value'}
>>> x = {}
>>> y
{'key':'value'}

B. If you want to clear all the elements in the original dictionary, you must use the clear method.

>>> 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 pair (this method does a shallow copy because the value itself is the same, not a copy)
When a value is replaced in a copy, the original dictionary is unaffected, but if a value is changed, the original dictionary changes. ]

>>> 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]}

The way to avoid this problem is to use depth copy-deepcopy (), which copies all the values.

>>> x = {'a':1,'b':[2,3,4]}
>>> y = x.copy()
>>> z = x.deepcopy()
>>> x['a'].append(5)
>>> y 
 {'a':1,5,'b':[2,3.4]}
>>> z
 {'a':1,'b':[2,3,4]}

1.4.3 fromkeys
The fromkeys method USES the given keys to create a new dictionary, each key has a default value of None, and can be called directly on all dictionaries of type dict. If you don't want to use the default values, you can provide the values yourself.

>>> {}.fromkeys(['name','age'])
{'age':None,'name':None}
>>>
>>> dict.fromkeys(['name','age'],'unknow')
{'age':'unknow','name':'unknow'}

1.4.4 the get
The get method is a more relaxed way to access dictionary items. When you use get to access a key that doesn't exist, you get a value of None. You can also customize the "default" value, replacing None.

>>> d = {}
>>> print d.get('name')
None
>>> d.get("name",'N/A')
'N/A'
>>> d[''name] = 'Eric'
>>> d.get('name')
'Eric'

1.4.5 has_key
The has_key method checks whether the dictionary contains the given key. D.h. as_key (k)

>>> d = {}
>>> d.has_key('name')
False

1.4.6 the items and the iteritems
The items method returns all dictionary items as a list, but each item in the list (key, value) is returned in no particular order. The iteritems method does much the same thing, but returns an iterator object instead of a list:

>>> d = {'a':1,'b':2,'c':3}
>>>d.items
[('a',1),('b',2),('c',3)]
>>> it = d.iteritems()
>>> it
<dictionary-iteritems object at 169050>
>>> list(it)
[('a',1),('b',2),('c',3)]

1.4.7 keys and iterkeys
The keys method returns the keys in the dictionary as a list, while iterkeys returns a key-specific iterator.

1.4.8 pop method
The pop method is used to get the value for the given key and then remove the key-value pair from the dictionary.

>>> d = {'a':1,'b':2,'c':3}
>>> d.pop('a')
>>> d
{'b':2,'c':3}

1.4.10 setdefault
The setdefault method is somewhat similar to the get method in that it can obtain the value associated with a given key and set the corresponding key value if the dictionary does not contain the given key.

>>> d = {}
>>> d.setdefault('name','N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d.setdefault('name',A)
'N/A'

In the example above, when the key exists, return the default value (optional) and update the dictionary accordingly, if the key exists, return its corresponding value, but do not change the dictionary.

1.4.11 update
The update method can use one dictionary entry to update another dictionary. Supplied dictionary entries are added to the old dictionary and overwritten if they have the same key.

>>> 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 values in the dictionary as a list (iterator for the return value of itervalues), which, unlike the list of return keys, can contain duplicate elements.

>>> 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]


Related articles: