python data structure algorithm question 11: keys in the dictionary map multiple values

question:

How to implement a dictionary with one key corresponding to multiple values ​​(also called multidict)?

solution:

A dictionary is a mapping of one key to a single value. If you want a key to map multiple values, then you need to put the multiple values ​​into another container, such as a list or set. For example, you can construct such a dictionary like this:

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

Choosing to use a list or a set depends on your actual needs. You should use a list if you want to keep the insertion order of elements, and a set if you want to remove duplicate elements (and don't care about the order of the 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 value corresponding to each key at the beginning, so you only need to focus on adding elements.

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)

It should be noted that defaultdict will automatically create 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 such a feature, you can use the setdefault() method on a regular dictionary instead.

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

Because each call must create a new instance of the initial value (the empty list [] in the example program).

Generally speaking, creating a multi-value mapping dictionary is very simple. However, if you choose to implement it yourself, initializing the value may be a bit troublesome.

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

If you use defaultdict, the code will be more concise:

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

おすすめ

転載: blog.csdn.net/m0_68635815/article/details/135439492