1.1 字典中的键映射多个值
可以使用 collections 模块中的 defaultdict 来构造这样的字典,该字典可以将键映射多个值
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
# {'a': [1, 2], 'b': [4]}
1.2 字典按序输出
为了能控制一个字典中元素的顺序,可以使用collections模块中的 OrderedDict 类。 在迭代操作的时候它会保持元素被插入时的顺序。
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
print(key, d[key])
1.3 字典的运算
为了对字典值执行计算操作,通常需要使用 zip() 函数先将键和值反转过来
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')
1.4 查找两字典的相同点
可以通过一些集合操作,但只支持字典的 keys() 或者 items()方法
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
# Find keys in common
a.keys() & b.keys() # { 'x', 'y' }
# Find keys in a that are not in b
a.keys() - b.keys() # { 'z' }
# Find (key,value) pairs in common
a.items() & b.items() # { ('y', 2) }