Home > Article > Backend Development > How to implement one-key multi-value dictionary in Python
The content of this article is about the implementation of one-key multi-value dictionary in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Requirements
We want a word that can map keys to multiple values (the so-called one-key multi-value dictionary)2. Solution
A dictionary is an associative container, and each key is mapped to a separate value. If you want a key to be mapped to multiple values, you need to save these multiple values into another container (list or set).
You can create a dictionary like this:
d={ ‘a’:[1,2,3], 'b':[4,5] }
Or you can create it like this:
d={ 'a':{1,2,3}, 'b':{4,5} }
Whether to use a list or a set depends entirely on the intent of the application. If you want to preserve the order in which elements were inserted, use a list. If you want to eliminate duplicate elements (and don't care about their ordering), use a set.
In order to easily create such a dictionary, you can use the defaultdict class in the collections module. One feature of defaultdict is that it automatically initializes the first value, 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) print(d) d=defaultdict(set) d['a'].add(1) d['a'].add(2) d['b'].add(4) print(d)
Result:
defaultdict(<class 'list'>, {'a': [1, 2], 'b': [4]}) defaultdict(<class 'set'>, {'a': {1, 2}, 'b': {4}})
The above is the detailed content of How to implement one-key multi-value dictionary in Python. For more information, please follow other related articles on the PHP Chinese website!