使用python list comprehension更新字典值 [英] use python list comprehension to update dictionary value

查看:69
本文介绍了使用python list comprehension更新字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个词典列表,如果关键价格等于

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 it possible to do something like that? I have tried also with

a.update({'price':0})

但效果不佳...

推荐答案

赋值是语句,并且这些语句在列表推导中不可用.只需使用普通的for循环即可:

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]

这篇关于使用python list comprehension更新字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆