sum value of two different dictionaries which is having same key

前端 未结 3 490
既然无缘
既然无缘 2021-01-19 22:04

i am having two dictionaries

first = {\'id\': 1, \'age\': 23}
second = {\'id\': 4, \'out\': 100} 

I want output dictionary as

{\'id\': 5, \         


        
3条回答
  •  离开以前
    2021-01-19 22:49

    If you want to add values from the second to the first, you can do it like this:

    first = {'id': 1, 'age': 23}
    second = {'id': 4, 'out': 100}
    
    for k in second:
        if k in first:
            first[k] += second[k]
        else:
            first[k] = second[k]
    print first
    

    The above will output:

    {'age': 23, 'id': 5, 'out': 100}
    

提交回复
热议问题