我正在尝试实现类似于 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)
可能有点难读。
最佳答案
您的代码没有任何问题。
您可以通过构造一个生成器并对其调用 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'
关于python - 在字典中查找键列表返回首先找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094725/