Python (data structure and algorithm [3]) and python (advanced tutorial)
Maps keys to multiple values in the dictionary.
One-click multi-value dictionary
d = {'a':[1,2,3], 'b':[4,5]}e = {'a':{1,2,3}, 'b':{4,5}}
Availablefrom collections import defaultdict
The default dictionary class is used. One feature of the default dictionary class is to automatically initialize the first value. You only need to pay attention to adding elements.
from collections import defaultdictd = defaultdict(list)d['a'].append(1)d['a'].append(4)...d = defaultdict(set)d['a'].add(5)...
Example:
d = defaultdict(list)for key, value in pairs: d[key].append(value)
Keep the dictionary in order
from collections import OrderedDictd = OrderedDict()d['grok'] = 4d['foo'] = 1d['abr'] = 2for key in d: print(key, d[key])
Output:
grok 4foo 1abr 2
When the dictionary is iterated, it will strictly follow the initial addition order of the elements.
Dictionary-related computing problems
Prices = {'acme ': 45.23, 'aap': 612.78, 'ibm': 205.55, 'hpq': 37.20, 'fb ': 10.75} # Use zip () reverse the dictionary key and value to min_price = min (zip (prices. values (), prices. keys () max_price = max (zip (prices. values (), prices. keys () print (min_price) print (max_price) # To sort data, you only need to use the sorted function price_sorted = sorted (zip (prices. values (), prices. keys () for key, value in price_sorted: print (key, value)
Output:
(10.75, 'FB')(612.78, 'AAPL')10.75 FB37.2 HPQ45.23 ACME205.55 IBM612.78 AAPL
If you do not usezip()
, What will happen?
Prices = {'acme ': 45.23, 'aap': 612.78, 'ibm': 205.55, 'hpq': 37.20, 'fb ': 10.75} print (min (prices )) # Only the print (min (prices. values () # Only search for values. values cannot be mapped to keys. // Add prices = {'aaa': 34, 'bbb ': 34} print (min (zip (prices. values (), prices. keys () # Compare the value size when the value is equal after the reversal
Search for similarities between the two dictionaries
a = { 'x' : 1, 'y' : 2, 'z' : 3}b = { 'w' : 10, 'x' : 11, 'y' : 2}print('Common keys:', a.keys() & b.keys())print('Keys in a not in b:', a.keys() - b.keys())print('(key,value) pairs in common:', a.items() & b.items()
Output:
Common keys: {'y', 'x'}Keys in a not in b: {'z'}(key,value) pairs in common: {('y', 2)}