我有2个字典,其中int值为键。我想从字典中删除键相同的值。
示例:
dictA={'key1':3, 'key2':4, 'key3':9, 'key5':5}
dictB={'key1':2, 'key2':5, 'key3':5, 'key4':4}
输出我想要的内容:
difference = {'key1':1,'key2':1,'key3':4,'key4':4,'key5':5}
答案 0 :(得分:2)
>>> dictA={'key1':3, 'key2':4, 'key3':9, 'key5':5}
>>> dictB={'key1':2, 'key2':5, 'key3':5, 'key4':4}
>>> dict( (k, abs(dictA.get(k, 0) - dictB.get(k, 0))) for k in set(dictA.keys())|set(dictB.keys()))
{'key3': 4, 'key2': 1, 'key1': 1, 'key5': 5, 'key4': 4}
>>> _ == {'key1':1,'key2':1,'key3':4,'key4':4,'key5':5}
True
完全按照要求。使用Python 2.7.3进行测试。