连接多个字典以创建新列表,并将值作为原始字典的值列表 [英] Join multiple dicts to create new list with value as list of values of original dict

查看:62
本文介绍了连接多个字典以创建新列表,并将值作为原始字典的值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7,并且在这里查看了几种解决方案,如果您知道要合并多少个词典,这些解决方案将起作用,但是我可以使用2到5个之间的任何东西.

I'm on Python 2.7 and have looked at several solutions here which works if you know how many dictionaries you are merging, but I could have anything between 2 to 5.

我有一个循环,该循环生成具有相同键但值不同的字典.我想将新值添加到先前的值中.

I have a loop which generates a dict with the same keys but different values. I want to add the new values to the previous.

例如:

for num in numbers:
    dict = (function which outputs a dictionary)
    [merge with dictionary from previous run of the loop]

所以,如果:

dict (from loop one) = {'key1': 1,
 'key2': 2,
 'key3': 3}

dict (from loop two) = {'key1': 4,
 'key2': 5,
 'key3': 6}

结果字典为:

dict = {'key1': [1,4]
 'key2': [2,5],
 'key3': [3,6]}

推荐答案

使用defaultdict:

In [18]: def gen_dictionaries():
    ...:     yield {'key1': 1, 'key2': 2, 'key3': 3}
    ...:     yield {'key1': 4, 'key2': 5, 'key3': 6}
    ...:

In [19]: from collections import defaultdict

In [20]: final = defaultdict(list)

In [21]: for d in gen_dictionaries():
    ...:     for k, v in d.iteritems():
    ...:         final[k].append(v)
    ...:

In [22]: final
Out[22]: defaultdict(list, {'key1': [1, 4], 'key2': [2, 5], 'key3': [3, 6]})

这篇关于连接多个字典以创建新列表,并将值作为原始字典的值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆