【问题标题】:How can I get a value only if it exist else return an empty dict in one line?How can I get a value only if it exist else return an empty dict in one line?
【发布时间】:2022-12-27 21:41:39
【问题描述】:

How to I check if a value exist and then return it and if it doesnt, return an empty dict {} (or any other operation) in one line?

I currently do the following which I feel could be done in a much morepythonway:

if (test[0].value):
   value = test[0].value
else
   value = {}

【问题讨论】:

  • What do you mean with "exist"? Your current code has no existence check.

标签: python


【解决方案1】:

You can use a ternary conditional/statement:

value = test[0].value if test[0].value else {}

【讨论】:

  • Or use or ...
猜你喜欢
  • 1970-01-01
  • 2022-11-20
  • 2022-12-01
  • 2022-12-01
  • 2021-07-18
  • 2022-12-27
  • 2022-12-01
  • 2022-12-02
  • 2022-12-26
相关资源
最近更新 更多