Associating Multiple Values with Each Key in a Dictionary
Credit: Michael Chermside
Problem
You need a dictionary that maps each key to multiple values.
Solution
By nature, a dictionary is a one-to-one mapping, but it’s not hard to make it one-to-many—in other words, to make one key map to multiple values. There are two possible approaches, depending on how you want to treat duplications in the set of values for a key. The following approach allows such duplications:
d1 = {}
d1.setdefault(key, []).append(value)while this approach automatically eliminates duplications:
d2 = {}
d2.setdefault(key, {})[value] = 1Discussion
A normal dictionary performs a simple mapping of a key to a value.
This recipe shows two easy, efficient ways to achieve a mapping of
each key to multiple values. The semantics of the two approaches
differ slightly but importantly in how they deal with duplication.
Each approach relies on the setdefault method of a
dictionary to initialize the entry for a key in the dictionary, if
needed, and in any case to return said entry.
Of course, you need to be able to do more than just add values for a key. With the first approach, which allows duplications, here’s how to retrieve the list of values for a key:
list_of_values = d1[key]
Here’s how to remove one value for a key, if you
don’t mind leaving empty lists as items of
d1 when the last value for a key is removed:
d1[key].remove(value)
Despite the empty lists, it’s still easy to test for the existence of a key with at least ...