Книга: Practical Programming, Fourth Edition
Назад: Storing Data Using Dictionaries
Дальше: Using the in Operator on Tuples, Sets, and Dictionaries

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 task 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 set, to keep track of the values associated with a key. If you 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 to the dictionary of observations to birds:

 >>>​​ ​​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,​​ ​​counts​​ ​​in​​ ​​bird_to_observations.items():
 ...​​ ​​if​​ ​​counts​​ ​​not​​ ​​in​​ ​​observations_to_birds_list:
 ...​​ ​​observations_to_birds_list[counts]​​ ​​=​​ ​​set()
 ...​​ ​​observations_to_birds_list[counts].add(bird)
 ...
 >>>​​ ​​observations_to_birds_list
 {5: {'canada goose'}, 1: {'snow goose', 'northern fulmar'},
  2: {'long-tailed jaeger'}}

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 an empty set. After that, the key associated with it in the original dictionary is appended to its set 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
 ...​​ ​​counts_sorted​​ ​​=​​ ​​sorted(observations_to_birds_list.keys())
 >>>​​ ​​for​​ ​​count​​ ​​in​​ ​​counts_sorted:
 ...​​ ​​birds​​ ​​=​​ ​​", "​​.join(observations_to_birds_list[count])
 ...​​ ​​print(f​​'{count} : {birds}'​​)
 ...
 1 : snow goose, northern fulmar
 2 : long-tailed jaeger
 5 : canada goose

The loop passes over each key in the inverted dictionary. The items in the set associated with each key are combined into one comma-and-space-separated string using the str.join method that takes a list of strings and combines them into one string using its object (str) as the “glue.”

Назад: Storing Data Using Dictionaries
Дальше: Using the in Operator on Tuples, Sets, and Dictionaries