Inverting a Dictionary
You might want to print the birds in another order—in order of the number of observations, for example. To do this, you need to invert the dictionary; that is, create a new dictionary in which you use the values as keys and the keys as values. This is a little trickier than it first appears. There’s no guarantee that the values are unique, so you have to handle what are called collisions. For example, if you invert the dictionary {’a’: 1, ’b’: 1, ’c’: 1}, a key would be 1, but it’s not clear what the value associated with it would be.
Since you’d like to keep all of the data from the original dictionary, you may need to use a collection, such as a list, to keep track of the values associated with a key. If we go this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access