Python241820
Python241820

Reputation: 1527

Problems comparing different dictionaries in python

I have the following dictionaries :

dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]

dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]

The question is: how to add the numbers that have the same code

For example, in "dict1" the code "dx22a" has the number 2 and the "dict2" the code " dx22a " is number 9 , so the result is 11 .

help and thanks

Upvotes: 0

Views: 70

Answers (2)

Copy and Paste
Copy and Paste

Reputation: 526

dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
dict3 = []
for key, value in [(i['code'], i['number']) for i in dict1]:
    for value2 in ([q['number'] for q in dict2 if q['code'] == key]):
        dict3.append({'code': key,'number': value + value2})
print (dict3)

This assumes that you only want dict3 to have keys that appear in both dict1 and dict2. Also that your intended output is the same format as dict1 and dict2 (a list of dictionaries). In addition that there is only one of each code in dict1 and dict2

Upvotes: 1

taesu
taesu

Reputation: 4570

dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
consolidated = {i['code']:i['number'] for i in dict1}
for i in dict2:
    if i['code'] in consolidated:
        consolidated[i['code']] += i['number']
    else:
        consolidated[i['code']] = i['number']
print(consolidated)

Upvotes: 1

Related Questions