在字典列表中查找和更新字典的值 [英] find and update a value of a dictionary in list of dictionaries

查看:85
本文介绍了在字典列表中查找和更新字典的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I find the dictionary with value user7 then update it's match_sum eg add 3 to the existing 4.

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

我有这个,并且不确定这样做是否是最佳实践.

I have this, and am not sure if its the best practice to do it.

>>> for x in l:
...     if x['user']=='user7':
...         x['match_sum'] +=3

推荐答案

您还可以使用

You can also use 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)

打印:

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

请注意,如果在调用 next()时未指定 default (第二个参数),则会引发 StopIteration 异常:

Note that if default (second argument) is not specified while calling next(), it would raise StopIteration exception:

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

这是如果指定 default 会发生的情况:

And here's what would happen if default is specified:

>>> next((item for item in l if item['user'] == 'unknown user'), 'Nothing found')
'Nothing found'

这篇关于在字典列表中查找和更新字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆