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' ?
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')
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.
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.
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")
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