我有两个字典。我想请您帮助解决以下问题:
第一个字典的值是第二个字典中的一个或多个键。像这样:
如何将第二个的值嵌套在第一个的值中?:
dict3=[
REQ-1:{value-1:{pcr-1,pcr-8},value-2:{pcr-2,pcr-3,pcr-4}},
REQ-2:{},
REQ-3:{value-3:{...},value-6:{...},value-10:{...}}
,...]
提前谢谢你
您可以通过迭代第一个字典来实现。您可以使用for循环或使用词典生成器来执行此操作。
假设第一个字典中的每个值实际上都存在于第二个字典中:
# For loop
dict3 = {} # Create an empty dictionary for us to populate
for key in dict1: # Iter over each of the keys in dict1
subdict = {} # This will be the nested dictionary
for item in dict1[key]: # Iter over each item in the list at that location in the dict
subdict[item] = dict2[item] # Get the corresponding list from dict2 and store it in the nested dictionary
dict3[key] = subdict # store the nested dictionary
# Dictionary generator
dict3 = {key: {item: dict2[item] for item in dict1[key]} for key in dict1}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句