Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit the values in a list of dictionaries?

Tags:

python

my_dicts = [      { 'key1' : 'value1',       'key2' : 'value2' },      { 'key1' : 'value1',         'key2' : 'value2' },      { 'key1' : 'value1',         'key2' : 'value2' }] 

What would be the most efficient way to replace all instances of 'value2' with 'value3' ?

like image 983
dave Avatar asked Nov 27 '10 10:11

dave


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')

Can values in dictionaries be changed?

Change elements in a dictionaryWe can change the value of an item by accessing the key using square brackets ([]). To modify multiple values at once, we can use the . update() method, since this function overwrites existing keys.

How do you update multiple values in a dictionary?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.


1 Answers

I did not do any timings, but you probably can't get much better than

for d in my_dicts:     d.update((k, "value3") for k, v in d.iteritems() if v == "value2") 

Update for Python3

for d in my_dicts:     d.update((k, "value3") for k, v in d.items() if v == "value2") 
like image 172
Sven Marnach Avatar answered Oct 14 '22 12:10

Sven Marnach