Python - 逆字典值列表
给定字典作为值列表,将其反转,即将列表中的元素映射到键并创建新的值列表。
Input : test_dict = {1: [2, 3], 2: [3], 3: [1]}
Output : {2: [1], 3: [1, 2], 1: [3]}
Explanation : List elements mapped with their keys.
Input : test_dict = {1: [2, 3, 4]}
Output : {2: [1], 3: [1], 4: [1]}
Explanation : List elements mapped with their keys.
方法:使用 defaultdict() + 循环
这是可以执行此任务的一种方式。在此,我们使用字典列表初始化结果键,并使用循环迭代为每个值分配其键,并改造结果字典值列表。
Python3
# Python3 code to demonstrate working of
# Inverse Dictionary Values List
# Using
from collections import defaultdict
# initializing dictionary
test_dict = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing empty list as Values
res = defaultdict(list)
# using loop to perform reverse mapping
for keys, vals in test_dict.items():
for val in vals:
res[val].append(keys)
# printing result
print("The required result : " + str(dict(res)))
输出
The original dictionary is : {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}
The required result : {2: [1, 4], 3: [1, 2], 1: [3, 4]}