简体   繁体   English

将两个词典中的值组合到一个列表中

[英]Combining the values in two dictionaries into a list

In python if I have two dictionaries, specifically Counter objects that look like so 在python中如果我有两个字典,特别是Counter对象看起来像这样

c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})

Can I combine these dictionaries so that the results is a dictionary of lists, as follows: 我可以组合这些词典,以便结果是列表字典,如下所示:

c3 = {'item1': [4,6], 'item2':[2,2], 'item3': [5,1], 'item4': [3], 'item5': [9]}

where each value is a list of all the values of the preceding dictionaries from the appropriate key, and where there are no matching keys between the two original dictionaries, a new kew is added that contains a one element list. 其中每个值是来自相应键的前面词典的所有值的列表,并且在两个原始词典之间没有匹配键的情况下,添加包含一个元素列表的新键。

from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
    for k,v in c.iteritems():
        c3.setdefault(k, []).append(v)

c3 is now: {'item1': [4, 6], 'item2': [2, 2], 'item3': [5, 1], 'item4': [3], 'item5': [9]} c3现在是: {'item1': [4, 6], 'item2': [2, 2], 'item3': [5, 1], 'item4': [3], 'item5': [9]}

Or with a list comprehension: 或者列表理解:

from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
merged = {}
for k in set().union(c1, c2):
    merged[k] = [d[k] for d in [c1, c2] if k in d]

>>> merged
{'item2': [2, 2], 'item3': [5, 1], 'item1': [4, 6], 'item4': [3], 'item5': [9]}

Explanation 说明

  1. Throw all keys that exist into an anonymous set. 将所有存在的密钥丢弃到匿名集中。 (It's a set => no duplicate keys) (这是一个set =>没有重复的键)
  2. For every key, do 3. 对于每一把钥匙,做3。
  3. For every dictionary d in the list of dictionaries [c1, c2] 对于词典列表中的每个字典d [c1, c2]
    • Check whether the currently being processed key k exists 检查当前正在处理的密钥k是否存在
      • If true: include the expression d[k] in the resulting list 如果为true:在结果列表中包含表达式d[k]
      • If not: proceed with next iteration 如果不是:继续下一次迭代

Here is a detailed introduction to list comprehension with many examples. 以下是列表理解的详细介绍,包含许多示例。

You can use defaultdict : 你可以使用defaultdict

>>> from collections import Counter, defaultdict
>>> c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
>>> c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
>>> c3 = defaultdict(list)
>>> for c in c1, c2:
...     for k, v in c.items():
...         c3[k].append(v)
... 
>>> c3
defaultdict(<type 'list'>, {'item2': [2, 2], 'item3': [5, 1], 'item1': [4, 6],
'item4': [3], 'item5': [9]})

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

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