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

2024-06-23 03:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

还有一个列表,比如:

list1 = [3, 6]

我想更新dict1或创建另一个列表,如下所示:

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

我该怎么做?


Tags: 列表字典domaincountgeometrylist1dict1ratios
3条回答

你可以这样做:

for i, d in enumerate(dict1):
    d['count'] = list1[i]

你可以这样做:

# list index
l_index=0

# iterate over all dictionary objects in dict1 list
for d in dict1:

    # add a field "count" to each dictionary object with
    # the appropriate value from the list
    d["count"]=list1[l_index]

    # increase list index by one
    l_index+=1

此解决方案不会创建新列表。相反,它会更新现有的dict1列表。

>>> 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'}]

相关问题 更多 >

    热门问题