problem: 怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?
answer:
eg1:
考虑下面的股票名和价格映射字典:
prices = {‘ACME‘: 45.23,‘AAPL‘: 612.78,‘IBM‘: 205.55,‘HPQ‘: 37.20,‘FB‘: 10.75}
为了对字典值执行计算操作,通常需要使用zip()函数先将键和值反转过来.下面是查找最小和最大股票价格和股票值的代码:
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‘)
类似的,可以使用zip() 和sorted() 函数来排列字典数据:
prices_sorted = sorted(zip(prices.values(), prices.keys()))
# prices_sorted is [(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
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
eg2:
字典值相同,键不同,比较值的大小
>>> prices = { ‘AAA‘ : 45.23, ‘ZZZ‘: 45.23 }
>>> min(zip(prices.values(), prices.keys()))
(45.23, ‘AAA‘)
>>> max(zip(prices.values(), prices.keys()))
(45.23, ‘ZZZ‘)