use python list comprehension to update dictionary value

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

    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.

提交回复
热议问题