从另一个列表中使用键值对更新Python字典列表

12

假设我有以下 Python 字典的列表:

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

并且一个类似于以下列表:

list1 = [3, 6]

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

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

我应该如何做到这一点?


根据示例,这个问题的标题应该是:“从另一个列表更新Python字典值的列表”。从当前的标题中,我会期望list1 = [('Ratios', 3), ('Geometry', 6)]。 - yucer
4个回答

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

谢谢。第二个解决方案在当前形式下会产生错误。 - Harshil Parikh
你正在使用Python 3吗?我可能会改成跨平台兼容的。 - jamylak
哪个在计算上更快? - amc
@amc 可能不值得担心 :P 但可以在其上运行一些 timeit 测试 - jamylak

6
你可以这样做:
for i, d in enumerate(dict1):
    d['count'] = list1[i]

3
你可以这样做:
# 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列表。


非常冗长的Python代码,但是解释得非常清楚。 - jamylak
1
是的,你说得对!它很冗长。但既然这里有其他不那么冗长的答案,我认为添加一个更详细的解决方案也是可以的。 - Thanasis Petsas

0
使用列表推导式是Pythonic的做法。
[data.update({'count': list1[index]}) for index, data in enumerate(dict1)]

dict1 将会被更新为来自 list1 的相应值。


1
使用列表推导式进行变异不是Pythonic。请使用简单的for循环。 - jamylak
对一个字典进行更新操作是在原地进行的,不会返回输出。data.update() 的返回值为 None。你将得到输出 [None, None, ....] - Manoj Sahu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接