One key in Python dictionary corresponds to multiple values

Python's dictionary is a key corresponding to a value. If you want a key to correspond to multiple values, you can use the following methods to achieve it.

Method 1: Create a key corresponding list

name_list = ['Mary', 'Jack']
age_list = [10, 12]
stu_dict = {
    
    
    'name': name_list,
    'age': age_list
}

print(stu_dict)

The output is as follows:

{
    
    'name': ['Mary', 'Jack'], 'age': [10, 12]}

Method 2: Use the dict.setdefault() method

stu_dict_1 = {
    
    }
key1 = 'name'
key2 = 'age'
# 使key对应一个空列表,并使用.append()方法对空列表进行元素的添加
stu_dict_1.setdefault(key1, []).append('Mary')
stu_dict_1.setdefault(key1, []).append('Jack')
stu_dict_1.setdefault(key2, []).append(10)
stu_dict_1.setdefault(key2, []).append(12)

print(stu_dict_1)

The output is as follows:

{
    
    'name': ['Mary', 'Jack'], 'age': [10, 12]}

Method 3: Use collections.defaultdict class

from collections import defaultdict
stu_dict_2 = defaultdict(list)
stu_dict_2['name'].append('Mary')
stu_dict_2['name'].append('Jack')
stu_dict_2['age'].append(10)
stu_dict_2['age'].append(12)

print(stu_dict_2)

The output is as follows:

defaultdict(<class 'list'>, {
    
    'name': ['Mary', 'Jack'], 'age': [10, 12]})

Defaultdict is a subclass of Python's built-in dict class, which uses a factory_function as input. This factory_function can be list, set, str, etc.

dict = defaultdict(factory_function)

In actual use, in addition to needing a dictionary with one key corresponding to multiple values, we may also need to deduplicate multiple values. In this case, we only need to create a dictionary of defaultdict(set). The example is as follows:

stu_dict_3 = defaultdict(set)
stu_dict_3['name'].add('Mary')
stu_dict_3['name'].add('Jack')
stu_dict_3['age'].add(10)
stu_dict_3['age'].add(10)

print(stu_dict_3)

The output is as follows:

defaultdict(<class 'set'>, {
    
    'name': {
    
    'Mary', 'Jack'}, 'age': {
    
    10}})

Guess you like

Origin blog.csdn.net/u012856866/article/details/132429336