Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1408
眼角桃花
眼角桃花 2020-11-27 09:33

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not

21条回答
  •  旧巷少年郎
    2020-11-27 09:42

    My recipe of symmetric difference between two dictionaries:

    def find_dict_diffs(dict1, dict2):
        unequal_keys = []
        unequal_keys.extend(set(dict1.keys()).symmetric_difference(set(dict2.keys())))
        for k in dict1.keys():
            if dict1.get(k, 'N\A') != dict2.get(k, 'N\A'):
                unequal_keys.append(k)
        if unequal_keys:
            print 'param', 'dict1\t', 'dict2'
            for k in set(unequal_keys):
                print str(k)+'\t'+dict1.get(k, 'N\A')+'\t '+dict2.get(k, 'N\A')
        else:
            print 'Dicts are equal'
    
    dict1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
    dict2 = {1:'b', 2:'a', 3:'c', 4:'d', 6:'f'}
    
    find_dict_diffs(dict1, dict2)
    

    And result is:

    param   dict1   dict2
    1       a       b
    2       b       a
    5       e       N\A
    6       N\A     f
    

提交回复
热议问题