Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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

data = ...
for a indata:
    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', 0if a['price'] == ''else a['price']) for a indata]

Solution 2:

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

[a.update(price=0) for a indataif a['price']=='']

without assignment will update the list...

Solution 3:

It is bad practice, but possible:

importoperator

l = [
    {'price': '', 'name': 'Banana'},
    {'price': 0.59, 'name': 'Apple'},
    {'name': 'Cookie', 'status': 'unavailable'}
]

[operator.setitem(p, "price", 0) for p in l if"price"in p and not p["price"]]

The cases in which there's no key "price" is handled and price is set to 0 if p["price"] is False, an empty string or any other value that python considers as False.

Note that the list comprehension returns garbage like [None].

Solution 4:

Yes you can.

You can't use update directly to dict because update is returns nothing and dict is only temporary variable in this case (inside list comprehension), so it will be no affect, but, you can apply it to iterable itself because iterable is persistance variable in this case.

instead of using

[my_dict['k'] = 'v'for my_dict in iterable]  # As I know, assignment not allowed in list comprehension

use

[iterable[i].update({'k': 'v'}) for i in range(len(iterable))]  # You can use enumerate also

So list comprehension itself will be return useless data, but your dicts will be updated.

Post a Comment for "Use Python List Comprehension To Update Dictionary Value"