Defaultdict Default Dictionary
- The Defaultdict (default dictionary) in the collections module, which can be used to construct a dictionary such as "one key map multiple values"
- If you want to keep the elements in the order of insertion, you should use list, if you want to remove the duplicate elements, use set
Import Import defaultdict
D=defaultdict (list) /
D= { ' a ' : [1< Span class= "P", 23, ' B ' Span class= "P" >: [45 }e = { ' a ' : {123 }, ' B ' : {4 Span class= "Mi" >5}}
- Note that the defaultdict will automatically create a mapped entity for the key that will be accessed, even if there is no such key in the current dictionary
fromCollectionsImportdefaultdict
D=defaultdict (list) d[1].append ('a') d[1].append ('b') d[2].append ('a')Print(D[0]) []//even though we did not assign a value to d[0, we still have a pit for this position.Print(d) defaultdict (<class 'List'{0: [], 1: ['a','b'], 2: ['a']}) Q=defaultdict (set) Q[0].add ('A0') Q[0].add ('B0') Q[0].add ('C0') q[1].add ('D1')Print(q) defaultdict (<class 'Set'{0: {'B0','C0','A0'}, 1: {'D1'}})
SetDefault
p={}p.setdefault ('1', []). Append ('a') P.setdefault ('1', []). Append ('b') P.setdefault ('2', []). Append ('C')Print(p[0]) keyerror:0#Contrary to the above, this does not occupy the pit.Print(p) {'2': ['C'],'1': ['a','b']}
Create a multi-valued mapping dictionary
D = {} for in pairs: if not in D: = [] = defaultdict (list) for in pairs: d[key].append ( Value)
[How do keys in the py3]--dictionary map multiple values?] How are dictionaries sorted?