在字典列表中查找和更新一个值。

7
我该如何查找值为user7dictionary,然后更新它的match_sum,例如在现有值4的基础上加3。
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

7
“list”是一个不好的变量名。除此之外,这段代码看起来还不错。 - karthikr
@karthikr 谢谢您指出这一点。我已经重命名了该列表。 - Alexxio
2个回答

11

你也可以使用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异常:

>>> 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,将会发生以下情况:

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

太好了!实际上,如果没有找到匹配项,我想做一些事情。帮了很大的忙。 - Alexxio

-1

如果有人想直接更新列表中存在的字典键值

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

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