I have two dictionaries. I would like to request your kind help to solve the following issue:
The values of the first dictionary are one or more of the keys from the second. Sometinhg like that:
How can I nest the values of the second into the values of the first one?:
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:{...}}
,...]
Thank you so much in advance
You can do so by iterating over the first dictionary. You can either do this using a for loop or with a dictionary generator.
Assuming every value in the first dictionary actually exists in the second:
# 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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.