Problem
How do I perform some computational operations (such as minimum, maximum, sort, etc.) in a data dictionary?
Solution Zip ()
1. In order to perform a calculation on a dictionary value, it is often necessary to use zip()
a function to reverse the key and value.
2. Similarly, you can also use the zip()
and sorted()
functions to arrange the dictionary data
Prices = { 'ACME': 37.20, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}Print(min (prices), max (prices))#perform normal math operations directly on a dictionary, which only operates on keys
AAPL IBM
Print # can be resolved through the values function of the dictionary, but only the values are visible when output
10.75 612.78
Print (min (prices,key=Lambda# can be solved by Min/max's key property function, but the output is not as good to see
Fb
Print (min (Zip (prices.values (), Prices.keys () ))) # A tuple sequence that "reverses" the Dictionary to (Value,key) by Zip ()
(10.75, ' FB ')
Print (Sorted (Zip (prices.values (), Prices.keys () )) # If you happen to have the same values, the results are returned based on the sort result of key.
[('FB' 'ACME' 'HPQ') 'IBM'AAPL')]
3. When performing these calculations, it is important to note that the zip()
function creates an iterator that is accessible only once
prices_and_names=Zip (prices.values (), Prices.keys ())print(max (prices_and_names)) ( ' AAPL ' Print(max (prices_and_names)) # The second time you use it, it's an error. is an empty Sequence
[py3]--How to perform some computational operations in the data dictionary (e.g., max, sort, etc.)