![](/img/trans.png)
[英]Compare the keys of two dictionaries and create a dictionary with key, value pairs that does not match the key in the other dictionary - Python
[英]“Adding” dictionaries in python if some (key, value) pairs match
三個字典:
d0 = {"a": "hello", "b": "world", "c": 11}
d1 = {"a": "hello", "b": "world", "c": 100}
d2 = {"a": "goodbye", "b": "world", "c": 10}
它們應該放在我反復添加的字典列表中。
dictionaries = [d0]
如果“ a”和“ b”是相同的(str)值,如何合並字典並將“ c”的整數值加在一起?
希望的結果:
d3 = {"a": "hello", "b": "world", "c": 111}
d2 = {"a": "goodbye", "b": "world", "c": 10}
dictionaries = [d2, d3] # any order
將您的c
值收集到以a, b
鍵為鍵的字典中; 使用collections.defaultdict()
對象使此操作變得容易一些:
from collections import defaultdict
keyed = defaultdict(int)
for d in (d0, d1, d2):
keyed[(d['a'], d['b'])] += d['c']
dictionaries = [{'a': a, 'b': b, 'c': c} for (a, b), c in keyed.items()]
如果特定鍵還不是字典的一部分,則keyed
defaultdict
對象的默認值為0
(調用int
會產生0
)。 然后,對於'a'
和'b'
值的給定組合,上述循環將'c'
所有值相加。
演示:
>>> from collections import defaultdict
>>> d0 = {"a": "hello", "b": "world", "c": 11}
>>> d1 = {"a": "hello", "b": "world", "c": 100}
>>> d2 = {"a": "goodbye", "b": "world", "c": 10}
>>> keyed = defaultdict(int)
>>> for d in (d0, d1, d2):
... keyed[(d['a'], d['b'])] += d['c']
...
>>> keyed
defaultdict(<type 'int'>, {('hello', 'world'): 111, ('goodbye', 'world'): 10})
>>> [{'a': a, 'b': b, 'c': c} for (a, b), c in keyed.items()]
[{'a': 'hello', 'c': 111, 'b': 'world'}, {'a': 'goodbye', 'c': 10, 'b': 'world'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.