For example
sample = [
{'one':'test', 'two': 'hello'},
{'one':'test', 'two': 'world'},
{'one': 'test', 'two': 'python'}
]
I want to change value of each 'one' from 'test' to 'done'
For example
sample = [
{'one':'test', 'two': 'hello'},
{'one':'test', 'two': 'world'},
{'one': 'test', 'two': 'python'}
]
I want to change value of each 'one' from 'test' to 'done'
Use a for loop and reassign the values of the keys:
for i in sample:
i['one'] = 'done'
sample
>>>[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]
If some dicts in your list might not have a 'one' key put the reassign in a try block:
for i in sample:
try:
i['one'] = 'done'
except KeyError:
pass
In Python3, you can use dictionary unpacking:
sample = [{'one': 'test', 'two': 'hello'}, {'one': 'test', 'two': 'world'}, {'one': 'test', 'two': 'python'}]
new_sample = [{**i, **{'one':'done'}} for i in sample]
Output:
[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]
For Python2, use a list comprehension to create the new dictionary:
new_sample = [{a:'done' if a == 'one' else b for a, b in i.items()} for i in sample]
Output:
[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]