抓取无,dict中默认值



我有一个字典,里面有一些值。现在在获取值的时候,我想检查值是否为None,将其替换为""

a = {'x' : 1, 'y': None}
x = a.get('x', 3) # if x is not present init x with 3
z = a.get('z', 1) # Default value of z to 1
y = a.get('y', 1) # It will initialize y with None
# current solution I'm checking
if y is None:
y = ""

我想要的是单行(python方式)。我可以这样做

# This is one way I can write but 
y = "" if a.get('y',"") is None else a.get('y', "")

但据我所知,一定有更好的方法来做这件事。任何帮助

如果您关心的唯一假值是None'',您可以这样做:

y = a.get('y', 1) or ''

Jasmijn的回答非常清楚。如果您需要容纳其他错误值,并且坚持在一行中完成,则可以使用赋值表达式:

y = "" if (initial := a.get('y', "")) is None else initial

但我个人更喜欢单独的if检查,以确保清晰度。

y = a.get('y',"") or ""

最新更新