繁体   English   中英

比较2个字典并减去键

[英]Compare 2 dictionary's and subtract the keys

我有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}
>>> 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测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM