0

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'

watthecode
  • 41
  • 1
  • 1
  • 5

2 Answers2

2

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
Primusa
  • 13,136
  • 3
  • 33
  • 53
0

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'}]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102