Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying list of dictionary using list comprehension

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}  ]
like image 655
Gambit1614 Avatar asked Dec 18 '22 22:12

Gambit1614


1 Answers

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}]
like image 139
jezrael Avatar answered Dec 20 '22 11:12

jezrael