Problem: Perform a variety of calculations (such as minimum, maximum, sort) on the data in a dictionary.
Solution: Use ZIP () to "invert" the key-value pair of the dictionary to a value-key pair sequence.
For example, the following dictionary holds the stock name and the corresponding price:
>>> prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}>>>prices{'HPQ': 37.2,'IBM': 205.55,'FB': 10.75,'ACME': 45.23,'AAPL': 612.78}>>> Min_price =min (Zip (prices.values (), Prices.keys ())) The order of the parameters in #注意zip (x, y)>>> Max_price =max (Zip (prices.values (), Prices.keys ()))>>>Min_price (10.75,'FB')>>>Max_price (612.78,'AAPL')>>> 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')]
>>> Min_price2 =min (Zip (prices)) #错误用法>>>Min_price2 ('AAPL',)>>> Max_price2 =Max (Zip (prices)) #错误用法>>>Max_price2 ('IBM',)>>> Min_price3 =min (Zip (Prices.keys (), Prices.values ())) #zip () parameter is incorrect in order to get the wrong value>>>Min_price3 ('AAPL', 612.78)>>> Max_price3 =max (Zip (Prices.keys (), Prices.values ())) #zip () parameter is incorrect in order to get the wrong value >>>Max_price3 ('IBM', 205.55)>>>
When doing these calculations, note that zip () creates an iterator whose contents can only be consumed once. For example:
>>> pirces_and_names=Zip (prices.values (), Prices.keys ())>>> pirces_and_names <zip object at 0x023bdfa8>>>> min (pirces_and_names) ('FB') >>> Max (pirces_and_names)Traceback (most recent): "<pyshell# 25> ", line 1, in <module> Max (pirces_and_names) Valueerror:max () arg was an empty sequence
Note: When comparing (value,key) pairs, it happens that more than one entry has the same value, then key will be used as the basis for determining the result.
>>> prices={'AAA': 45.23,'ZZZ': 45.23} >>> min (Zip (prices.values (), Prices.keys ())) ('AAA') >>> max (Zip (prices.values (), Prices.keys ())) ('ZZZ')
"Python Cookbook" "Data Structure and algorithm" 8. Dictionary-related Computational problems