gpt4 book ai didi

python - 如何合并具有多个键值对的两个字典

转载 作者:行者123 更新时间:2023-12-05 04:11:37 25 4
gpt4 key购买 nike

我有两个字典,如下所示。我在使用 Python 2.7。

entries_per_day = [ {"time": "October 1", "entries": "5" }, 
{"time": "October 2", "entries": "3" },
{"time": "October 3", "entries": "1" },
{"time": "October 4", "entries": "0" },
{"time": "October 5", "entries": "23" }]

views_per_day = [ {"time": "October 1", "views": "9" },
{"time": "October 2", "views": "3" },
{"time": "October 3", "views": "5" },
{"time": "October 4", "views": "6" },
{"time": "October 5", "views": "32" }]

如何将两个词典合并为第三个词典,以便输出如下所示:

area_chart_data = [ {"time": "October 1", "entries": "5", "views": "9" }, 
{"time": "October 2", "entries": "3", "views": "3" },
{"time": "October 3", "entries": "1", "views": "5" },
{"time": "October 4", "entries": "0", "views": "6" },
{"time": "October 5", "entries": "23", "views": "32" }]

我希望“entries”和“views”键值对与它们最初所在的日期位于同一数据段中。

最佳答案

由于字典条目似乎匹配,只需zip 两个列表并用第二个字典更新一个字典,然后插入列表。

area_chart_data = []

for e,v in zip(entries_per_day,views_per_day):
e.update(v)
area_chart_data.append(e)

print(area_chart_data)

结果:

[{'views': '9', 'time': 'October 1', 'entries': '5'}, {'views': '3', 'time': 'October 2', 'entries': '3'}, {'views': '5', 'time': 'October 3', 'entries': '1'}, {'views': '6', 'time': 'October 4', 'entries': '0'}, {'views': '32', 'time': 'October 5', 'entries': '23'}]

它改变了第一个列表。如果你不想这样,你必须在更新之前执行 e = e.copy()

编辑:如 this Q&A 中所述,使用“dict 添加”的单行代码:

area_chart_data = [dict(e, **v) for e,v in zip(entries_per_day,views_per_day)]

关于python - 如何合并具有多个键值对的两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com