Python 连接多个dict以创建新列表,其值为原始dict的值列表

Python 连接多个dict以创建新列表,其值为原始dict的值列表,python,loops,dictionary,Python,Loops,Dictionary,我使用的是Python2.7,这里介绍了几种解决方案,如果您知道要合并多少个词典,这些解决方案是有效的,但我可以使用2到5之间的任何解决方案 我有一个循环,它生成一个具有相同键但不同值的dict。我想将新值添加到上一个值 例如: for num in numbers: dict = (function which outputs a dictionary) [merge with dictionary from previous run of the loop] 因此,如果:

我使用的是Python2.7,这里介绍了几种解决方案,如果您知道要合并多少个词典,这些解决方案是有效的,但我可以使用2到5之间的任何解决方案

我有一个循环,它生成一个具有相同键但不同值的dict。我想将新值添加到上一个值

例如:

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将是:

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]})

以通用方式实现这一点的一种方法是使用
set
找到
dict
s的键的并集,然后使用字典理解获得所需的dict,如下所示:

>>> dict_list = [d1, d2]  # list of all the dictionaries which are to be joined

 # set of the keys present in all the dicts; 
>>> common_keys = set(dict_list[0]).union(*dict_list[1:])

>>> {k: [d[k] for d in dict_list if k in d] for k in common_keys}
{'key3': [3, 6], 'key2': [2, 5], 'key1': [1, 4]}
其中
d1
d2
为:

d1 = {'key1': 1,
      'key2': 2,
      'key3': 3}

d2 = {'key1': 4,
      'key2': 5,
      'key3': 6}
解释:此处,
dict\u list
是要组合的所有
dict
对象的列表。然后我在所有dict对象中创建
公共_键
键集。最后,我通过使用字典理解(使用带过滤器的嵌套列表理解)创建了一个新字典


根据OP的评论,因为所有的dict都有相同的键,所以我们可以跳过set的用法。因此,代码可以写成:

>>> dict_list = [d1, d2]  

>>> {k: [d[k] for d in dict_list] for k in dict_list[0]}
{'key3': [3, 6], 'key2': [2, 5], 'key1': [1, 4]}
输出如下所示:


{'p':[90],'m':[2,1],'o':[7],'n':[4,3]}

两个dict之间的键总是一样的吗?对不起,是的,忘了提到,键总是一样的
>>> dict_list = [d1, d2]  

>>> {k: [d[k] for d in dict_list] for k in dict_list[0]}
{'key3': [3, 6], 'key2': [2, 5], 'key1': [1, 4]}
dict1 = {'m': 2, 'n':4, 'o':7, 'p':90}
dict2 = {'m': 1, 'n': 3}


dict3 = {}

for key,value in dict1.iteritems():
    if key not in dict3:
        dict3[key] = list()
    dict3[key].append(value)


for key,value in dict2.iteritems():
    if key not in dict3:
        dict3[key] = list()
    dict3[key].append(value)


print(dict3)