合并具有相同键和不同值的两个字典 [英] Consolidating two dictionaries with the same keys and different values
本文介绍了合并具有相同键和不同值的两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 collection.Counter()s,它们都是相同的键,所以它们看起来像这样:
I have two collection.Counter()s, both of which of the same keys, so they look something like this:
01: 3
02: 2
03: 4
01: 8
02: 10
03: 13
我希望最终结果看起来更像这样:
I want the final result to look a bit more like this:
01: [3, 8]
02: [2, 10]
03: [4, 13]
我将如何合并它们?
推荐答案
您可以使用 字典理解:
dict1 = {1: 3, 2: 2, 3: 4 }
dict2 = {1: 8, 2: 10, 3: 13 }
dict3 = { k: [ dict1[k], dict2[k] ] for k in dict1 }
# Result:
# dict3 = {1: [3, 8], 2: [2, 10], 3: [4, 13]}
这篇关于合并具有相同键和不同值的两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文