So I have the following list of dictionary
myList = [{'one':1, 'two':2,'three':3},
{'one':4, 'two':5,'three':6},
{'one':7, 'two':8,'three':9}]
This is just an example of a dictionary that I have. My question is, it possible to somehow modify say key two
in all the dictionary to become twice their value, using list comprehension ?
I know how to use list comprehension to create new list of dictionary, but don't know how to modify them, I have come up with something like this
new_list = { <some if condiftion> for (k,v) in x.iteritems() for x in myList }
I am not sure how to specify a condition in the <some if condiftion>
, also is the nested list comprehension format I am thinking of correct ?
I want the final output as per my example like this
[ {'one':1, 'two':4,'three':3},{'one':4, 'two':10,'three':6},{'one':7, 'two':16,'three':9} ]
Use list comprehension with nested dict comprehension:
new_list = [{ k: v * 2 if k == 'two' else v for k,v in x.items()} for x in myList]
print (new_list)
[{'one': 1, 'two': 4, 'three': 3},
{'one': 4, 'two': 10, 'three': 6},
{'one': 7, 'two': 16, 'three': 9}]
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