Introduction
Dictionary (dict) is built into a Python data structure, key (key) and the value (value) by a plurality of key-value pairs separated by a colon, (,) separated by commas for each key, the entire dictionary comprising ({}), the key must be unique, and can take any type of value in braces, but the key must be immutable types, such as strings, numbers, or tuples.
Underlying hash table used to associate the key and value, dict is disordered. Features include:
● find and insert the fast, the key will not increase slowed;
● need to take up more memory
So, dict is a trade space for time data structure, used to quickly find the required scene.
Operation: common method
get()
Returns the value of the specified key, if the key is not present, the default value (the default is None) is returned, without error, syntax dict.get (key).
dict_1['age'] = 24 In [7]: print(dict_1.get('age')) 24 In [11]: print(dict_1.get('nama')) None In [12]: print(dict_1['nama']) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-12-ef61a380920e> in <module> ----> 1 print(dict_1['nama']) KeyError: 'nama'
Use in operator to determine whether the key exists in the dictionary, there is the return True, otherwise it returns False, the syntax is: key in dict. key in dict
In [15]: dict_1 Out[15]: {'name': None, 'age': 24, 'sex': None} In [16]: print('name' in dict_1) True In [17]: print('nama' in dict_1) False
items () implemented in the function uses the python 2 has_key () method.
Return may traverse a list form (key, value) tuples array syntax is dict.items ().
In [18]: dict_1 Out[18]: {'name': None, 'age': 24, 'sex': None} In [19]: print(dict_1.items()) dict_items([('name', None), ('age', 24), ('sex', None)]) In [20]: for key, value in dict_1.items(): ...: print(key, value) ...: name None age 24 sex None
To return a list of all the keys dictionary: dict.keys () Keys ()
In [21]: dict_1 Out[21]: {'name': None, 'age': 24, 'sex': None} In [22]: print(dict_1.keys()) dict_keys(['name', 'age', 'sex'])
Returns all values in list form in the dictionary: dict.values () values ()
In [21]: dict_1 Out[21]: {'name': None, 'age': 24, 'sex': None} In [22]: print(dict_1.keys()) dict_keys(['name', 'age', 'sex'])
The syntax is: dict_1.update (dict_2), used to update the key value dict_2 dict_1 if the same key will be covered. update ()
In [31]: dict_1 Out[31]: {'name': None, 'age': 24, 'sex': None, 'sub_name': 'Tony'} In [32]: dict_2 Out[32]: {'name': 'Mary', 'age': 18, 'sex': None, 'sub_name': ''} In [33]: dict_1.update(dict_2) In [34]: dict_1 Out[34]: {'name': 'Mary', 'age': 18, 'sex': None, 'sub_name': ''}
Delete all entries in the dictionary, dict.clear (), for example: the Clear ()
In [1]: dict_1 = dict(name="Tony", age=24) In [2]: dict_2 = dict_1 In [3]: print(dict_2) {'name': 'Tony', 'age': 24} In [4]: dict_2.clear() In [5]: dict_2 Out[5]: {} In [6]: dict_1 Out[6]: {}
A shallow copy of the original dictionary, the dictionary returns a new key-value pairs having the same, dict.copy (), for example: Copy ()
In [1]: dict_1 = dict(name='Tony', info=['boy', 24]) In [2]: dict_3 = dict_1.copy() In [3]: dict_3['name'] = "Ring" In [4]: dict_3['info'].remove('boy') In [5]: dict_3 Out[5]: {'name': 'Ring', 'info': [24]} In [6]: dict_1 Out[6]: {'name': 'Tony', 'info': [24]}
Create a new dictionary, dict.fromkeys (seq [, value] ), to make a sequence of elements seq dictionary key, all keys corresponding to the value of the dictionary initial value, wherein the value is optional, defaults to None. Suitable for data initialization, for example: fromkeys ()
In [1]: info = ['name', 'age', 'sex'] In [2]: dict_1 = dict.fromkeys(info) In [3]: dict_1 Out[3]: {'name': None, 'age': None, 'sex': None}
The combined Dictionary common operations
There are four ways:
Conventional treatment
In [15]: dict_1 Out[15]: {'Tony': 24} In [16]: dict_2 Out[16]: {'ben': 18} In [17]: dict3 = dict() In [18]: for key, value in dict_1.items(): ...: dict_3[key] = value ...: In [19]: for key, value in dict_2.items(): ...: dict_3[key] = value ...: In [20]: dict_3 Out[20]: {'Tony': 24, 'ben': 18}
Dictionary means dict (d1, ** d2) method update ()
In [33]: dict_1 Out[33]: {'Tony': 24} In [34]: dict_2 Out[34]: {'ben': 18} In [35]: dict_3 = dict(dict_1, **dict_2) In [36]: dict_3 Out[36]: {'Tony': 24, 'ben': 18}
Dictionary derivations Advanced
And deriving a list of similar type, the advantage of the underlying C implementation, will be much faster, is recommended.
Swapping keys of the dictionary
Derivations can easily use a dictionary for a dictionary of key-value pairs:
In [42]: dict_4 Out[42]: {24: 'Tony', 18: 'ben'} In [43]: dict_3 Out[43]: {'Tony': 24, 'ben': 18} In [44]: dict_4 = {k:v for v, k in dict_3.items()} In [45]: dict_4 Out[45]: {24: 'Tony', 18: 'ben'}
I want to create a dictionary, which itself is a subset of another dictionary. Extract a subset from the dictionary
for example:
In [88]: a = {'Ben': 18, 'Jack': 12, 'Ring': 23, 'Tony': 24} In [89]: b = {k:v for k, v in a.items() if v > 18} In [90]: b Out[90]: {'Ring': 23, 'Tony': 24}
Before Python3.6 dictionary is unordered, but sometimes we need to maintain orderly dictionary, orderDict ordering can be achieved on the basis of the dictionary dict on the orderly here refers to the insertion of the key according to the dictionary arranged in order, so to achieve a dict FIFO, when the capacity limit is exceeded, the oldest added delete key. Generates an ordered dictionary
For example:
In [49]: from collections import OrderedDict In [50]: ordered_dict = OrderedDict([('a', 2), ('b', 4), ('c', 5)]) In [51]: for key, value in ordered_dict.items(): ...: print(key, value) ...: a 2 b 4 c 5
Principle: Internal OrderedDict maintains a doubly linked list, where it will join the order to arrange key elements, which also causes the size of OrderedDict is 2 times more than ordinary dictionary. We can see OrderedDict be inserted in accordance with the order to create a sort of dictionary.
The combined list of key same dictionary
It is a key to generate a so-called multi-value dictionary needs to be stored in a plurality of values corresponding to other containers such as a list or set, depending on whether the multi-value need to ensure uniqueness.
for example:
In [64]: from collections import defaultdict In [65]: a = [{'a': 1}, {'b': 3}, {'c': 4}, {'a':5}, {'b':2}, {'b': 4}] In [66]: b = defaultdict(list) In [67]: [b[k].append(v) for item in a for k, v in item.items()] Out[67]: [None, None, None, None, None, None] In [68]: b Out[68]: defaultdict(list, {'a': [1, 5], 'b': [3, 2, 4], 'c': [4]}) In [69]: b['a'] Out[69]: [1, 5]
Scene: Find the difference between the two dictionaries, including the same or identical key values. Look for similarities and differences between two dictionaries
Analysis: The dictionary is a mapping between the set of a series of keys, has the following characteristics:
keys () returns all keys in the dictionary, and the dictionary is to support key set of operations, and so using a cross set up keys to the dictionary processing;
items () returns (key, value) composed of objects, support the collection of operations;
values () does not support the set operation, because there is no guarantee that all values are unique, but if you have to judge the operation, can first be converted to a set of values to achieve.
For example:
In [78]: a = {'a':1, 'b':2, 'c':3} In [79]: b = {'b':3, 'c':3, 'd':4} In [80]: a.keys() & b.keys() Out[80]: {'b', 'c'} In [81]: a.keys() - b.keys() Out[81]: {'a'} In [82]: a.items() & b.items() Out[82]: {('c', 3)}
As another example, when you create a dictionary, you can remove certain key expectations:
In [85]: a Out[85]: {'a': 1, 'b': 2, 'c': 3} In [86]: c = {k: a[key] for k in a.keys() - {'b'}} In [87]: c Out[87]: {'a': 3, 'c': 3}