Home > Software design >  Hot add the values from one dictionary to another in python
Hot add the values from one dictionary to another in python

Time:05-27

I have two dictionaries.

Dict1={'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
Dict2={'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}

I want to take all key,value pairs from Dict1 and find according stock price in the second dictionary. Then I want to add stock price data in the first dictionary. Could you help me with the solution in python?

My desired output is:

Dict3={'comp1':{'Company name':'aaa','Industry':'aaa','Stock price':100},'comp2':{'Company name':'bbb','Industry':'bbb','Stock price':200}}

CodePudding user response:

For python 3.9 , you can use |:

Dict1 = {'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
Dict2 = {'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}

output = {k: d | Dict2[k] for k, d in Dict1.items()}

print(output)
# {'comp1': {'Company name': 'aaa', 'Industry': 'aaa', 'Stock price': 100}, 'comp2': {'Company name': 'bbb', 'Industry': 'bbb', 'Stock price': 200}}

For python versions before 3.9 (but still 3.5 ), it becomes slightly more verbose:

output = {k: dict((*d.items(), *Dict2[k].items())) for k, d in Dict1.items()}

If you happen to have python < 3.5, then you can use:

output = {k: d.copy() for k, d in Dict1.items()} # or, copy.deepcopy(Dict1)
for k, d in output.items():
    d.update(Dict2[k])

If you are fine with in-place modification of Dict1, then you don't need copying (the first line).

CodePudding user response:

Clear

dict1 = {'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
dict2 = {'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}
dict3 = {}

for k in dict1.keys():
    dict3[k]= {'Company name': dict1[k]['Company name'], 'Industry': dict1[k]['Industry'], 'Stock price': dict2[k]['Stock price']}
  • Related