The of list or collection of methods that map multiple values by keys in the Python dictionary

  • 2020-12-19 21:08:17
  • OfStack

A dictionary is a mapping of one key to one single value. If you want one key to map multiple values, you need to place the values in a different container, such as a list or collection. For example, you could construct a dictionary like this:


d = {
 'a' : [1, 2, 3],
 'b' : [4, 5]
}
e = {
 'a' : {1, 2, 3},
 'b' : {4, 5}
}

Whether you choose to use lists or collections depends on your actual needs. Use lists if you want to keep elements in their insertion order, and collections if you want to get rid of duplicate elements (and don't care about the order of elements).

You can easily use defaultdict in the collections module to construct such a dictionary. One feature of defaultdict is that it automatically initializes the initial value of each key, so you only need to focus on adding elements.

Such as:


from collections import defaultdict

d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)

d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)

Note that defaultdict automatically creates a mapping entity for the key to be accessed (even if such a key does not currently exist in the dictionary). If you don't need this feature, you can use the setdefault() method on a regular dictionary instead. Such as:


d = {} # A regular dictionary
d.setdefault('a', []).append(1)
d.setdefault('a', []).append(2)
d.setdefault('b', []).append(4)

But many programmers find setdefault() a little awkward to use. Each call creates an instance of a new initial value (the empty list [] in the example program).

discuss

In general, creating a multi-value mapping dictionary is easy. However, if you choose to implement it yourself, then initializing the value can be a bit of a hassle. You might implement it like this:


d = {}
for key, value in pairs:
 if key not in d:
  d[key] = []
 d[key].append(value)

The code is even cleaner if you use defaultdict:


d = defaultdict(list)
for key, value in pairs:
 d[key].append(value)

Related articles: