Python 在字典列表中查找并更新字典的值

Python 在字典列表中查找并更新字典的值,python,list,dictionary,Python,List,Dictionary,如何找到值为user7的dictionary,然后更新它的match\u sum例如将3添加到现有的4 l = [{'user': 'user6', 'match_sum': 8}, {'user': 'user7', 'match_sum': 4}, {'user': 'user9', 'match_sum': 7}, {'user': 'user8', 'match_sum': 2} ] 我有这个,不确定这是否是最好的做法

如何找到值为
user7
dictionary
,然后更新它的
match\u sum
例如将3添加到现有的4

l = [{'user': 'user6', 'match_sum': 8}, 
        {'user': 'user7', 'match_sum': 4}, 
        {'user': 'user9', 'match_sum': 7}, 
        {'user': 'user8', 'match_sum': 2}
       ]
我有这个,不确定这是否是最好的做法

>>> for x in l:
...     if x['user']=='user7':
...         x['match_sum'] +=3
您还可以使用:

印刷品:

[{'match_sum': 8, 'user': 'user6'},
 {'match_sum': 7, 'user': 'user7'},
 {'match_sum': 7, 'user': 'user9'},
 {'match_sum': 2, 'user': 'user8'}]
请注意,如果调用
next()
时未指定
default
(第二个参数),则会引发
StopIteration
异常:

>>> d = next(item for item in l if item['user'] == 'unknown user')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

如果有人想直接更新列表中任何键的值

l = [{'user': 'user6', 'match_sum': 8}, 
    {'user': 'user7', 'match_sum': 4}, 
    {'user': 'user9', 'match_sum': 7}, 
    {'user': 'user8', 'match_sum': 2}
    ] 
to_be_updated_data = {"match_sum":8}
item = next(filter(lambda x: x["user"]=='user7', l),None)
if item is not None:
    item.update(to_be_updated_data)
输出将是:

    [{'user': 'user6', 'match_sum': 8}, 
    {'user': 'user7', 'match_sum': 8}, 
    {'user': 'user9', 'match_sum': 7}, 
    {'user': 'user8', 'match_sum': 2}] 

list
是一个错误的变量名。除此之外,这段代码在我看来还行。@karthikr谢谢你指出这一点。我已重命名listPerfect!,如果找不到匹配项,我真的想做点什么。帮助很大。
l = [{'user': 'user6', 'match_sum': 8}, 
    {'user': 'user7', 'match_sum': 4}, 
    {'user': 'user9', 'match_sum': 7}, 
    {'user': 'user8', 'match_sum': 2}
    ] 
to_be_updated_data = {"match_sum":8}
item = next(filter(lambda x: x["user"]=='user7', l),None)
if item is not None:
    item.update(to_be_updated_data)
    [{'user': 'user6', 'match_sum': 8}, 
    {'user': 'user7', 'match_sum': 8}, 
    {'user': 'user9', 'match_sum': 7}, 
    {'user': 'user8', 'match_sum': 2}]