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
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')
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.
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), ...] .
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With