我正在使用Python 2.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 (from loop two) = {'key1': 4,
'key2': 5,
'key3': 6}
结果是dict:
dict = {'key1': [1,4]
'key2': [2,5],
'key3': [3,6]}
答案 0 :(得分:2)
使用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]})
答案 1 :(得分:0)
以通用方式实现此目的的一种方法是使用set
找到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_list
是您要合并的所有dict
个对象的列表。然后我在所有dict对象中创建common_keys
键集。最后,我正在使用字典理解创建一个新字典(使用嵌套列表理解和过滤器)。
根据OP的评论,由于所有的词组都拥有相同的键,我们可以跳过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]}
答案 2 :(得分:0)
//if foo is a function returning void but is declared in global space and not part of another class
TakesFun(bind(foo));
//if foo is a function returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj));
//if foo is a function taking an integer as argument and returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj, 5)); //5 is the argument supplied to function foo
输出如下:
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)