gpt4 book ai didi

python - 使用另一个列表中的键值对更新 python 字典列表

转载 作者:太空狗 更新时间:2023-10-29 17:37:55 26 4
gpt4 key购买 nike

假设我有以下 python 字典列表:

dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]

和一个像这样的列表:

list1 = [3, 6]

我想按如下方式更新 dict1 或创建另一个列表:

dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]

我该怎么做?

最佳答案

>>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
>>> l2 = [3, 6]
>>> for d,num in zip(l1,l2):
d['count'] = num


>>> l1
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]

另一种方法,这次使用不改变原始列表的理解:

>>> [dict(d, count=n) for d, n in zip(l1, l2)]
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]

关于python - 使用另一个列表中的键值对更新 python 字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10592674/

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