Skip to content
Advertisement

find and update a value of a dictionary in list of dictionaries

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

Advertisement

Answer

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)

prints:

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

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

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'
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement