First, Collections.defaultdict: multi-valued mapping dictionary
Defaultdict eliminates the process of initializing the container, the default value object is a container of the specified type
You can use the. Append when specifying list.
From collections Import DEFAULTDICTD = Defaultdict (list) d[' a '].append (1) d
Defaultdict (list, {' A ': [1]})
When you specify set, you can use. Add,
D = defaultdict (set) d[' A '].add (1) d[' A '].add (1) d
Defaultdict (set, {' A ': {1}})
The original dictionary can use the. SetDefault method to specify value as a container, but is not recommended, as follows,
D = {}d.setdefault (' a ', []). Append (1) d.setdefault (' A ', []). Append (2) d.setdefault (' B ', []). Append (3) d.setdefault (' C ' , {append}) #默认的dict对象没有add方法, not using the # # because the default method creates a new empty object each time a new element is added [], it is not recommended to D
{' A ': [1, 2], ' B ': [3], ' C ': {1, 2, 3}}
By the way, the content of the dictionary is the key value,
The ' a ' in D # Dictionary in is key
True
Second, collections. Ordereddict: Dictionary with Order
Ordereddict internally maintains a doubly linked list to record the order in which key values are inserted, update the key value does not affect the original order, insert key value is inserted at the end, so its memory consumption is twice times the normal dictionary ,
From collections Import ORDEREDDICTD = Ordereddict () d[' a '] = 1d[' c '] = 3d[' b '] = 2print (d, D.items ())
Ordereddict (' A ', 1), (' C ', 3), (' B ', 2)])
Odict_items (' A ', 1), (' C ', 3), (' B ', 2)])
An ordered dictionary is actually used in conjunction with JSON to output information,
Import json# encode the dictionary and use Orderddict to control the order of the Fields Json.dumps (d)
' {' A ': 1, ' C ': 3, ' B ': 2} '
"Collections" Data structures and algorithms _ container-type value dictionary & Order Dictionary