Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use python list comprehension to update dictionary value

I have a list of dictionaries and would like to update the value for key 'price' with 0 if key price value is equal to ''

data=[a['price']=0 for a in data if a['price']=='']

Is it possible to do something like that? I have tried also with

a.update({'price':0})

but did not work as well...

like image 402
user2950162 Avatar asked Apr 20 '14 12:04

user2950162


2 Answers

Assignments are statements, and statements are not usable inside list comprehensions. Just use a normal for-loop:

data = ...
for a in data:
    if a['price'] == '':
        a['price'] = 0

And for the sake of completeness, you can also use this abomination (but that doesn't mean you should):

data = ...

[a.__setitem__('price', 0 if a['price'] == '' else a['price']) for a in data]
like image 175
Markus Unterwaditzer Avatar answered Sep 28 '22 03:09

Markus Unterwaditzer


if you're using dict.update don't assign it to the original variable since it returns None

[a.update(price=0) for a in data if a['price']=='']

without assignment will update the list...

like image 27
Vinay G Avatar answered Sep 28 '22 03:09

Vinay G