Skip to content Skip to sidebar Skip to footer

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'

Solution 1:

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'] += 3print(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 calllast):
  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'

Solution 2:

If in case some one looking to directly update dictionay key's value present inside a list

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 isnotNone:
    item.update(to_be_updated_data)

Output will be:

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

Post a Comment for "Find And Update A Value Of A Dictionary In List Of Dictionaries"