use python list comprehension to update dictionary value

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

    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...

    0 讨论(0)
  • 2021-01-02 00:33

    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.

    0 讨论(0)
  • 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].

    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题