python - 在 Python 中,根据字典是否包含键为变量赋值的最小方法是什么?

标签 python dictionary lambda

我想以类似下面的方式访问字典中的一些值:

self.userName              = self.options["--username"]
self.files                 = self.options["--files"].split(",")
self.configurationFileName = self.options["--configuration"]

但是,这些键中的一些可能不存在于字典中——比方说“--files”可能不在其中。如果字典中不存在键,我希望将变量的值设置为 None,即 self.files = None。目前,我正在做类似以下的事情:

if "--files" in self.options:
    self.files = self.options["--files"].split(",")
else:
    self.files = None

是否有某种方法可以更简洁、更高效或更符合 Python 风格?为了清楚起见,我更希望在一行中完成此操作。谢谢!

最佳答案

默认使用get 和一个空字符串,如果是空字符串或空列表,则用None 代替:

self.files = self.options.get('--files', "").split(",") or None

这样 split 总是在有效对象上调用,如果对象为空,您将得到 None

编辑

实际上我做的测试使用了 split() which uses a different algorithm than 拆分(",")

所以要工作,应该是

self.files = self.options.get('--files', "").replace(',', '\n').split() or None

使用 set 操作的另一种方法:

self.files = set(self.options.get('--files', "").split(",")) ^ set(['']) or None

但是 self.files 是一个集合而不是一个列表。

事后思考:

我会做的是定义一个小的辅助类

class NoneFound:
  @classmethod
  def split(self, _):
    return None

然后简单地:

self.files = self.options.get('--files', NoneFound).split(',')

查看已定义的类:

>>> print {'--files': "a,b,c"}.get("--files", NoneFound).split(',')
['a', 'b', 'c']
>>> print {}.get("--files", NoneFound).split(',')
None

关于python - 在 Python 中,根据字典是否包含键为变量赋值的最小方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877749/

相关文章:

java - 在 Java 中定义 Map<String, Map<String, String>> 映射的最佳方法是什么?

c++ - 未评估上下文中的默认模板参数和 lambda : bug or feature?

python - 在 Python 中使用元组作为字典键

python - 带插值的 Matplotlib 二维图

python - 通过嵌套Python字典进行高效迭代

java - 如何交换 map 中的 key ?

java - 使嵌套的http请求java异步

Eclipse:有选择地转换为 lambda 表达式

Python xml 到 csv

python - .loc 用于 Pandas 中的分类索引