[英]Combining lists of dictionaries based on list index
我覺得這個問題以前肯定有人問過,但在 Stack Overflow 上找不到。
有沒有辦法根據列表索引優雅地組合多個字典列表? 見下文:
list_1 = [{'hello': 'world'}, {'foo': 'test'}]
list_2 = [{'a': 'b'}, {'c': 'd'}]
result = [{'hello': 'world', 'a': 'b'},
{'foo': 'test', 'c': 'd'}]
我知道我可以在技術上使用 for 循環,例如:
list_3 = []
for i in range(len(list_1)):
list_3.append({**list_1[i],**list_2[i]})
有沒有辦法通過列表理解來做到這一點? 另外,如果我涉及的列表超過 2 個或不知道字典列表的數量怎么辦?
這將執行您想要的操作:
result = [{**x, **y} for x, y in zip(list_1, list_2)]
# [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]
有關**
語法的解釋,請參閱PEP 448 。
對於通用解決方案:
list_1=[{'hello':'world'},{'foo':'test'}]
list_2=[{'a':'b'},{'c':'d'}]
list_3=[{'e':'f'},{'g':'h'}]
lists = [list_1, list_2, list_3]
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
result = [merge_dicts(*i) for i in zip(*lists)]
# [{'a': 'b', 'e': 'f', 'hello': 'world'}, {'c': 'd', 'foo': 'test', 'g': 'h'}]
對於通用解決方案,在 Python 3 中,您可以執行以下操作:
In [14]: from operator import or_
In [15]: from functools import reduce
In [16]: list_of_lists = [list_1, list_2]
In [17]: [dict(reduce(or_, map(dict.items, ds))) for ds in zip(*list_of_lists)]
Out[17]: [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]
在 Python 2 中,不需要導入reduce
,因為它已經在全局命名空間中,但是您需要使用dict.viewitems
而不是dict.items
:
[dict(reduce(or_, map(dict.viewitems, ds))) for ds in zip(*list_of_lists)]
請注意,我可以看到您的解決方案的唯一真正問題是它for i in range(...)
,當您應該只循環遍歷zip
pped 列表時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.