Home > database >  How to nest two dictionaries together based on identical values?
How to nest two dictionaries together based on identical values?

Time:04-08

I have two dictionaries and I am trying to nest them together to organize the values. I am so lost!


component_dict = {'11309': ['a','b', 'c'], 
                  '11525': ['d', 'e'] } 

sku_dict = {'a': 0.0,
           'b': 1500.0,
           'c': 1000.0,
           'd': 0.0,
           'e': 5.0" }

I am trying to nest the two dictionaries to make the new dictionary look like this:

       
final_dict: {'11309': {'a': 0, 'b': 1500,'c': 1000}, 
             '11525: {'d': 0, 'e': 5}}  

Thank you so much for your help!

CodePudding user response:

This one is a bit tricky, there are some libraries like collections in python you can use to help you achieve this a bit more elegantly, but I've written it out with a bit more verbosity to help with explanation. See below for your answer:

merged = {}

for x in component_dict:
    merged[x] = {y:sku_dict[y] for y in component_dict[x]}
    
print(merged)

CodePudding user response:

Use dictionary comprehension:

final_dict = {k: {x: sku_dict[x] for x in v} for k, v in component_dict.items()}

>>> final_dict
{'11309': {'a': 0.0, 'b': 1500.0, 'c': 1000.0}, 
 '11525': {'d': 0.0, 'e': 5.0}}
  • Related