Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 639
Alexxio Avatar asked Jul 31 '14 03:07

Alexxio


People also ask

How do you update a value in a dictionary list?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')

How do you find the value of the dictionary in a list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.

How do I extract a value from a dictionary?

If you only need the dictionary values -0.3246 , -0.9185 , and -3985 use: your_dict. values() . If you want both keys and values use: your_dict. items() which returns a list of tuples [(key1, value1), (key2, value2), ...] .


1 Answers

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'
like image 87
alecxe Avatar answered Sep 26 '22 16:09

alecxe