How to get the difference between two dictionaries in Python?

前端 未结 9 1355
庸人自扰
庸人自扰 2020-11-27 04:45

I have two dictionaries. I need to find the difference between the two which should give me both key and value.

I have searched and found some addons/packages like d

9条回答
  •  日久生厌
    2020-11-27 05:20

    What about this? Not as pretty but explicit.

    orig_dict = {'a' : 1, 'b' : 2}
    new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}
    
    updates = {}
    for k2, v2 in new_dict.items():
        if k2 in orig_dict:    
            if v2 != orig_dict[k2]:
                updates.update({k2 : v2})
        else:
            updates.update({k2 : v2})
    
    #test it
    #value of 'a' was changed
    #'v' is a completely new entry
    assert all(k in updates for k in ['a', 'v'])
    

提交回复
热议问题