假设我有以下 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/