Dav*_*agh 3 python dictionary list
在python中如果我有两个字典,特别是Counter对象看起来像这样
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
Run Code Online (Sandbox Code Playgroud)
我可以组合这些词典,以便结果是列表字典,如下所示:
c3 = {'item1': [4,6], 'item2':[2,2], 'item3': [5,1], 'item4': [3], 'item5': [9]}
Run Code Online (Sandbox Code Playgroud)
其中每个值是来自相应键的前面词典的所有值的列表,并且在两个原始词典之间没有匹配键的情况下,添加包含一个元素列表的新键.
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)
Run Code Online (Sandbox Code Playgroud)
c3 就是现在: {'item1': [4, 6], 'item2': [2, 2], 'item3': [5, 1], 'item4': [3], 'item5': [9]}
| 归档时间: |
|
| 查看次数: |
226 次 |
| 最近记录: |