简体   繁体   中英

How to nest the values of a first dictionary into the values of a second dictionary?

I have two dictionaries. I would like to request your kind help to solve the following issue:

  1. The first one has 339 keys-values pairs. The values may have a random lenght from cero to 10.
  2. The secong one has 215 keys-values pairs. In the same case, the values have a random lenght.

The values of the first dictionary are one or more of the keys from the second. Sometinhg like that:

  • dict1=[REQ-1:{value-1, value-2}, REQ-2:{}, REQ-3:{value-3, value-6, value-10},...]
  • dict2=[value-1:{pcr-1,pcr-8}, value-2:{pcr-2,pcr-3,pcr-4},....]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM