查找首先找到的字典返回键列表

时间:2018-01-04 11:54:45

标签: python

我试图实现类似于ansible with_first_found,

的东西
configuration = {
   "fedora-27"    : "edge-case options for fedora 27",
   "ubuntu-14.04" : "edge-case options for ubuntu 14.04",
   "fedora"       : "as long as it's fedora, these options are fine",
   "ubuntu"       : "these options are good for all ubuntu versions",
   "redhat"       : "options for rpm distros",
   "debian"       : "try these options for anything remotely resembling debian",
   "default"      : "/if/all/else/fails",
}

if __name__ == "__main__":

   distribution_release = "ubuntu-16.04"
   distribution = "ubuntu"
   os_family = "debian"

   lookup = [
      distribution_release,
      distribution,
      os_family,
      "default"
   ]

   for key in lookup:
      if key in configuration:
         first_found = configuration[key]
         break

   print(first_found)

现在这段代码做了我想要的,但我觉得有一种更好的方法来进行这种查找。这个for / if / break循环可以在单行中完成吗?

根据来自timgeb的评论,我更接近我的目标。

   first_found = next(configuration[key] for key in lookup if key in configuration)

可能有点难以阅读。

1 个答案:

答案 0 :(得分:4)

您的代码没有任何问题。

您可以通过构建生成器并在其上调用next来缩短它。

>>> demo = {1:2, 3:4, 5:6}
>>> next(demo[k] for k in (6,3,5) if k in demo)
4

这也允许使用默认值:

>>> next((demo[k] for k in (0,-1,-2) if k in demo), 'default')
'default'