字典运算
问题
在数据字典中执行一些计算操作(比如求最小值、最大值、排序)?
解决
对字典值执行计算操作,通常需要使用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
(10.75, 'FB')
>>> max_price = max(zip(prices.values(), prices.keys()))
>>> max_price
(612.78, 'AAPL')
还可以用zip
和sorted
函数
>>> prices_sorted = sorted(zip(prices.values(), prices.keys()))
>>> prices_sorted
[(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'), (612.78, 'AAPL')]
注意
zip
函数创建的是一个只能访问一次的迭代器
>>> prices_and_names = zip(prices.values(), prices.keys())
>>> print(min(prices_and_names)) # OK
(10.75, 'FB')
>>> print(max(prices_and_names))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence