Python241820 Python241820 - 7 months ago 10
Python Question

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

Answer
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)
Comments