如何在Python中组合两个不平衡列表中的两个字典?
目标是通过合并两个如何在Python中组合两个不平衡列表中的两个字典?,python,list,dictionary,Python,List,Dictionary,目标是通过合并两个词典,得到一个词典,每个词典都来自不同的列表 对于余额列表(即,如果列表具有相同的len),只需使用zip: first_list = [{'val': 1, 'item': 'item1'}, {'val': 2, 'item': 'item2'}, {'val': 3, 'item': 'item3'}] sec_list = [{'idx': 1, 'other': '1'}, {'idx': 2, 'other': '2'}, {'idx': 3, 'other': '
词典
,得到一个词典
,每个词典都来自不同的列表
对于余额列表(即,如果列表具有相同的len
),只需使用zip
:
first_list = [{'val': 1, 'item': 'item1'}, {'val': 2, 'item': 'item2'}, {'val': 3, 'item': 'item3'}]
sec_list = [{'idx': 1, 'other': '1'}, {'idx': 2, 'other': '2'}, {'idx': 3, 'other': '3'}]
new_result=[]
for first_list_x,sec_list_x in zip(first_list,sec_list):
new_result.append({**first_list_x, **sec_list_x})
产生
new_result = [{'val': 1,'item': 'item1', 'idx': 1, 'other': '1'}, \
{'val': 2,'item': 'item2', 'idx': 2, 'other': '2'}, \
{'val': 3,'item': 'item3', 'idx': 3, 'other': '3'}]
请注意,顺序很重要,因此,val:1
将与idx:1
保持在同一罩下
然而,如果两个列表的长度不相同,事情就变得更棘手了,如下所示:
first_list = [{'val': 1, 'item': 'item1'}, {'val': 2, 'item': 'item2'}, {'val': 3, 'item': 'item3'}]
sec_list = [{'idx': 1, 'other': '1'}, {'idx': 2, 'other': '2'}]
new_result=[]
for first_list_x,sec_list_x in zip(first_list,sec_list):
new_result.append({**first_list_x, **sec_list_x})
遗嘱产生
new_result=[{'val': 1, 'item': 'item1', 'idx': 1, 'other': '1'},
{'val': 2, 'item': 'item2', 'idx': 2, 'other': '2'}]
虽然代码产生了它应该输出的内容,但我希望在新的dict中有{'val':3,'item':'item3'}
。因此,预期的输出应该是
new_result = [{'val': 1,'item': 'item1', 'idx': 1, 'other': '1'}, \
{'val': 2,'item': 'item2', 'idx': 2, 'other': '2'}, \
{'val': 3,'item': 'item3'}]
我想知道如何实现上述不平衡列表的目标。另外,如果有比使用
zip
和{**x,**y}
快得多的其他建议,请谅解。您可以使用itertools
中的zip
,而不是zip
。使用zip
或zip\u longest
以及{**x,**y}
可能是最快的
>>> from itertools import zip_longest
>>>
>>> first_list = [{'val': 1, 'item': 'item1'}, {'val': 2, 'item': 'item2'}, {'val': 3, 'item': 'item3'}]
>>> sec_list = [{'idx': 1, 'other': '1'}, {'idx': 2, 'other': '2'}]
>>>
>>> [dict(**d1, **d2) for d1,d2 in zip_longest(first_list,sec_list, fillvalue={})]
[{'val': 1, 'item': 'item1', 'idx': 1, 'other': '1'},
{'val': 2, 'item': 'item2', 'idx': 2, 'other': '2'},
{'val': 3, 'item': 'item3'}]
您可以使用
itertools
中的zip\u longest
而不是zip
。使用zip
或zip\u longest
以及{**x,**y}
可能是最快的
>>> from itertools import zip_longest
>>>
>>> first_list = [{'val': 1, 'item': 'item1'}, {'val': 2, 'item': 'item2'}, {'val': 3, 'item': 'item3'}]
>>> sec_list = [{'idx': 1, 'other': '1'}, {'idx': 2, 'other': '2'}]
>>>
>>> [dict(**d1, **d2) for d1,d2 in zip_longest(first_list,sec_list, fillvalue={})]
[{'val': 1, 'item': 'item1', 'idx': 1, 'other': '1'},
{'val': 2, 'item': 'item2', 'idx': 2, 'other': '2'},
{'val': 3, 'item': 'item3'}]