Cuttings: Inverting (vs Zipping) Dictionary Values and Items Inverting (vs Zipping) Dictionary Values and Items | Cuttings
Things of interest.

October 6, 2016

Inverting (vs Zipping) Dictionary Values and Items

On the inversion of a dictionary's key/values.

David Beazley wrote, in Item 1.8 of Python Cookbook 3 (“Calculating with Dictionaries”):

In order to perform useful calculations on the dictionary contents, it is often useful to invert the keys and values of the dictionary using zip().

min_price = min(zip(prices.values(), prices.keys()))

… The solution involving zip() solves the problem by “inverting” the dictionary into a sequence of (value, key) pairs.


The above plagued me until I finally ‘got’ it. Here’s how I’d explain it instead:

  1. zip() does not actually ‘invert’ the dictionary. It only creates an iterable zip object.

  2. To actually make a dictionary from the zip object, apply dict() to it.

  3. The zip object merely preserves the order of its arguments; i.e. you get the ‘inverted’ dictionary because the above code uses values-keys (rather than keys-values).


prices = {
 'ACME': 45.23,
 'AAPL': 612.78,
 'IBM': 205.55,
 'HPQ': 37.20,
 'FB': 10.75

zipped_not_dict = zip(prices.values(), prices.keys())
zipped_dict = dict(zip(prices.values(), prices.keys()))

print(prices.values(), prices.keys(), sep="\n")
print(zipped_not_dict, zipped_dict, sorted(zipped_dict), sep="\n")

…which outputs:

dict_values([205.55, 45.23, 37.2, 10.75, 612.78])
dict_keys(['IBM', 'ACME', 'HPQ', 'FB', 'AAPL'])
<zip object at 0x0133B148>
{10.75: 'FB', 205.55: 'IBM', 45.23: 'ACME', 612.78: 'AAPL', 37.2: 'HPQ'}
[10.75, 37.2, 45.23, 205.55, 612.78]


Another Pythonic way to invert key-values is by dictionary comprehension:

reversed_key_value_dict = {v:k for k, v in dict_name.items()}


© 1997 - 2018 / Info