How to implement one-key multi-value dictionary in Python

不言
Release: 2018-10-11 14:20:53
forward
4573 people have browsed it

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]
}
Copy after login

Or you can create it like this:

d={
'a':{1,2,3},
'b':{4,5}
}
Copy after login

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)
Copy after login

Result:

defaultdict(<class &#39;list&#39;>, {'a': [1, 2], 'b': [4]})
defaultdict(<class &#39;set&#39;>, {'a': {1, 2}, 'b': {4}})
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!