简体   繁体   中英

look up list of keys in dictionary return first found

I'm trying to achieve something similar to 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)

Now this code does what I want, but I have a feeling there is a nicer way to do this lookup. Can this for/if/break loop be done in a one-liner?

A little closer to what I'm aiming for based on comments from timgeb.

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

It's a little hard to read maybe.

There's nothing wrong with your code.

You could shorten it by constructing a generator and calling next on it.

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

This also allows for a default value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM