use python list comprehension to update dictionary value

后端 未结 4 2104
我在风中等你
我在风中等你 2021-01-02 00:26

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          


        
4条回答
  •  庸人自扰
    2021-01-02 00:51

    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]
    

提交回复
热议问题