Python – 使用给定的列表创建嵌套字典
给定一个列表和字典,将列表的每个元素与字典的每个项目映射,形成嵌套字典作为值。
Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2]
Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}}
Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on.
Input : test_dict = {‘Gfg’ : 4}, test_list = [8]
Output : {8: {‘Gfg’: 4}}
Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}.
方法 #1:使用循环 + zip()
这是可以执行此任务的方式之一。在此,我们使用 zip() 组合两个列表,并使用循环来进行压缩键的迭代和字典构造。
Python3
# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using loop + zip()
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
# using zip() and loop to perform
# combining and assignment respectively.
res = {}
for key, ele in zip(test_list, test_dict.items()):
res[key] = dict([ele])
# printing result
print("The mapped dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using dictionary comprehension + zip()
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
# zip() and dictionary comprehension mapped in one liner to solve
res = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)}
# printing result
print("The mapped dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}
方法 #2:使用字典理解 + zip()
这是可以执行此任务的另一种方式。在此,我们执行与上述方法类似的任务,但在一个内衬中使用字典理解
Python3
# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using dictionary comprehension + zip()
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
# zip() and dictionary comprehension mapped in one liner to solve
res = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)}
# printing result
print("The mapped dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}