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

Ale*_*xio 4 python dictionary list

如何找到dictionary有值user7然后更新它,match_sum例如将3添加到现有4.

l = [{'user': 'user6', 'match_sum': 8}, 
        {'user': 'user7', 'match_sum': 4}, 
        {'user': 'user9', 'match_sum': 7}, 
        {'user': 'user8', 'match_sum': 2}
       ]
Run Code Online (Sandbox Code Playgroud)

我有这个,我不确定它是否是最好的做法.

>>> for x in l:
...     if x['user']=='user7':
...         x['match_sum'] +=3
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 6

您还可以使用next():

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

d = next(item for item in l if item['user'] == 'user7')
d['match_sum'] += 3
print(l)
Run Code Online (Sandbox Code Playgroud)

打印:

[{'match_sum': 8, 'user': 'user6'},
 {'match_sum': 7, 'user': 'user7'},
 {'match_sum': 7, 'user': 'user9'},
 {'match_sum': 2, 'user': 'user8'}]
Run Code Online (Sandbox Code Playgroud)

请注意,如果default在调用时未指定(第二个参数)next(),则会引发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
Run Code Online (Sandbox Code Playgroud)

如果default指定了会发生什么:

>>> next((item for item in l if item['user'] == 'unknown user'), 'Nothing found')
'Nothing found'
Run Code Online (Sandbox Code Playgroud)