2024-06-23 03:15:24 发布
网友
假设我有以下python字典列表:
dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
还有一个列表,比如:
list1 = [3, 6]
我想更新dict1或创建另一个列表,如下所示:
dict1
dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]
我该怎么做?
你可以这样做:
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'}]
你可以这样做:
你可以这样做:
此解决方案不会创建新列表。相反,它会更新现有的
dict1
列表。另一种方法是,这一次的列表理解不会改变原始的:
相关问题 更多 >
编程相关推荐