use python list comprehension to update dictionary value

后端 未结 4 2113
我在风中等你
我在风中等你 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:39

    It is bad practice, but possible:

    import operator
    
    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].

提交回复
热议问题