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

使用另一个列表中的键、值对更新python字典列表,python,list,dictionary,Python,List,Dictionary,假设我有以下python字典列表: dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}] 下面是一个列表: list1 = [3, 6] 我想更新dict1或创建另一个列表,如下所示: dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}] 我该怎么做 您可以这样做: for i, d in enumerate(dict1): d['cou

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

dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
下面是一个列表:

list1 = [3, 6]
我想更新
dict1
或创建另一个列表,如下所示:

dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]
我该怎么做

您可以这样做:

for i, d in enumerate(dict1):
    d['count'] = list1[i]
另一种方法是,这一次使用列表理解,不会改变原始内容:

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

# 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
列表。

使用列表理解将是pythonic的方法

[data.update({'count': list1[index]}) for index, data in enumerate(dict1)]

dict1
将使用
list1

中的相应值进行更新,对于Python来说非常详细,但是解释得非常好。是的,您是对的!它非常冗长。但是,由于这里还有其他不太详细的答案,我认为可以添加一个更具解释性的解决方案..谢谢你的详细解释。谢谢。第二个解决方案在其当前形式中产生了一个错误,您使用Python3吗?我可能会将其更改为交叉兼容。哪种计算速度更快?@amc可能不值得担心:P但可以在其上运行一些
timeit
s-1使用列表理解突变不是pythonic的。使用简单的for循环。在dict上更新work on reference不提供输出。data.update()返回None。根据示例,这个问题的标题应该是:“从另一个列表更新python字典值列表”。从当前的标题来看,我希望列表1=[('ratio',3),('Geometry',6)]
[data.update({'count': list1[index]}) for index, data in enumerate(dict1)]