How can I find the dictionary
with value user7
then update it’s match_sum
eg add 3 to the existing 4.
JavaScript
x
6
1
l = [{'user': 'user6', 'match_sum': 8},
2
{'user': 'user7', 'match_sum': 4},
3
{'user': 'user9', 'match_sum': 7},
4
{'user': 'user8', 'match_sum': 2}
5
]
6
I have this, and am not sure if its the best practice to do it.
JavaScript
1
4
1
>>> for x in l:
2
if x['user']=='user7':
3
x['match_sum'] +=3
4
Advertisement
Answer
You can also use next()
:
JavaScript
1
9
1
l = [{'user': 'user6', 'match_sum': 8},
2
{'user': 'user7', 'match_sum': 4},
3
{'user': 'user9', 'match_sum': 7},
4
{'user': 'user8', 'match_sum': 2}]
5
6
d = next(item for item in l if item['user'] == 'user7')
7
d['match_sum'] += 3
8
print(l)
9
prints:
JavaScript
1
5
1
[{'match_sum': 8, 'user': 'user6'},
2
{'match_sum': 7, 'user': 'user7'},
3
{'match_sum': 7, 'user': 'user9'},
4
{'match_sum': 2, 'user': 'user8'}]
5
Note that if default
(second argument) is not specified while calling next()
, it would raise StopIteration
exception:
JavaScript
1
5
1
>>> d = next(item for item in l if item['user'] == 'unknown user')
2
Traceback (most recent call last):
3
File "<stdin>", line 1, in <module>
4
StopIteration
5
And here’s what would happen if default
is specified:
JavaScript
1
3
1
>>> next((item for item in l if item['user'] == 'unknown user'), 'Nothing found')
2
'Nothing found'
3