Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以特定的方式合并两个词典?_Python_Python 3.x_Pandas - Fatal编程技术网

Python 如何以特定的方式合并两个词典?

Python 如何以特定的方式合并两个词典?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有两本字典,如: d1 = {'new_list1':['a', 'b', 'c', 'd'], 'new_list2':['a', 'b', 'd', 'e']} d2 = {'new_list1': [1,2,3,4], 'new_list2': [1,2,4,5]} 我希望输出像: d3 = {'new_list1':[['a',1],['b',2],['c',3],['d',4]], 'new_list2':[['a',1],['b',2],['d',4],['e',5]]} 要查

我有两本字典,如:

d1 = {'new_list1':['a', 'b', 'c', 'd'], 'new_list2':['a', 'b', 'd', 'e']}
d2 = {'new_list1': [1,2,3,4], 'new_list2': [1,2,4,5]}
我希望输出像:

d3 = {'new_list1':[['a',1],['b',2],['c',3],['d',4]], 'new_list2':[['a',1],['b',2],['d',4],['e',5]]}
要查看的要点: 1.两个词典的键数相同 2.列表形式的值可以有不同的长度,因此在不匹配的情况下需要填充为0

d3 = dict(zip(d1.keys(),[list(zip(d1[k], d2[k])) for k in d1]))
输出

{'new_list1': [('a', 1), ('b', 2), ('c', 3), ('d', 4)], 'new_list2': [('a', 1), ('b', 2), ('d', 4), ('e', 5)]}

如果可能,在两个字典列表之间匹配每个值,请使用:

out = {k:list(map(list, zip(v, d2[k]))) for k, v in d1.items()}
print (out)
{'new_list1': [['a', 1], ['b', 2], ['c', 3], ['d', 4]], 
 'new_list2': [['a', 1], ['b', 2], ['d', 4], ['e', 5]]}
如果长度不匹配,请使用:

或:


@jezrael-answer的更新。我认为没有必要将map的结果键入列表

from  itertools import zip_longest

d1 = {'new_list1':['a', 'b', 'c', 'd'], 'new_list2':['a', 'b']}
d2 = {'new_list1': [1,2,3], 'new_list2': [1,2,4,5]}

out = {k:map(list, zip_longest(v, d2[k], fillvalue=0)) for k, v in d1.items()}
或:


你试过什么了?
d1
d2
new_list2
看起来坏了。@BlackThunder我用了一个很长的方法,单独解析和附加,需要一些优化的解决方案,因为数据比较大。2个列表中的元素“new_list1,new_list2,等等”总是相同的,也可能不同?@Dhiraj:有一些“差距“在问题陈述中。如果另一个字典中缺少一个键,该怎么办?如果列表长度不同,会发生什么情况?请更新您的问题,并确保您解决了这些问题。请查看下面的答案。有什么问题吗?@AlbinAntony-这取决于python版本,如果使用
python3
,则获取
{'new\u list1':,'new\u list2':}
out = {k: list(map(list, zip_longest(d1[k], d2[k], fillvalue=0))) for k in d1}
print (out)
{'new_list1': [['a', 1], ['b', 2], ['c', 3], ['d', 0]], 
 'new_list2': [['a', 1], ['b', 2], [0, 4], [0, 5]]}
from  itertools import zip_longest

d1 = {'new_list1':['a', 'b', 'c', 'd'], 'new_list2':['a', 'b']}
d2 = {'new_list1': [1,2,3], 'new_list2': [1,2,4,5]}

out = {k:map(list, zip_longest(v, d2[k], fillvalue=0)) for k, v in d1.items()}
out = {k: map(list, zip_longest(d1[k], d2[k], fillvalue=0)) for k in d1}
print (out)
{'new_list1': [['a', 1], ['b', 2], ['c', 3], ['d', 0]], 
 'new_list2': [['a', 1], ['b', 2], [0, 4], [0, 5]]}