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 route, the inverse of the dictionary shown earlier would be {1: [’a’, ’b’, ’c’]}. Here’s a program to invert the dictionary of birds to observations:

 >>>​​ ​​bird_to_observations
 {'canada goose': 5, 'northern fulmar': 1, 'long-tailed jaeger': 2,
 'snow goose': 1}
 >>>
 >>>​​ # Invert the dictionary
 >>>​​ ​​observations_to_birds_list​​ ​​=​​ ​​{}
 >>>​​ ​​for​​ ​​bird,​​ ​​observations​​ ​​in​​ ​​bird_to_observations.items():
 ...​​ ​​if​​ ​​observations​​ ​​in​​ ​​observations_to_birds_list:
 ...​​ ​​observations_to_birds_list[observations].append(bird)
 ...​​ ​​else:
 ...​​ ​​observations_to_birds_list[observations]​​ ​​=​​ ​​[bird]
 ...
 >>>​​ ​​observations_to_birds_list
 {1: ['northern fulmar', 'snow goose'], 2: ['long-tailed jaeger'],
 5: ['canada goose']}

This program loops over each key/value pair in the original dictionary, bird_to_observations. If that value is not yet a key in the inverted dictionary, observations_to_birds_list, it is added as a key and its value is a single-item list containing the key associated with it in the original dictionary. On the other hand, if that value is already a key, then the key associated with it in the original dictionary is appended to its list of values.

Now that the dictionary is inverted, you can print each key and all of the items in its value list:

 >>>​​ # Print the inverted dictionary
 ...​​ ​​observations_sorted​​ ​​=​​ ​​sorted(observations_to_birds_list.keys())
 >>>​​ ​​for​​ ​​observations​​ ​​in​​ ​​observations_sorted:
 ...​​ ​​print(observations,​​ ​​':'​​,​​ ​​end=​​" "​​)
 ...​​ ​​for​​ ​​bird​​ ​​in​​ ​​observations_to_birds_list[observations]:
 ...​​ ​​print(​​' '​​,​​ ​​bird,​​ ​​end=​​" "​​)
 ...​​ ​​print()
 ...
 1 : northern fulmar snow goose
 2 : long-tailed jaeger
 5 : canada goose

The outer loop passes over each key in the inverted dictionary, and the inner loop passes over each of the items in the values list associated with that key.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.192