Pregunta

Is there an easy, readable and Pythonic way of extracting particular values from dict when I have list of keys?

I often find myself doing things like this:

uri = "http://%s:%s" % (self.options['listener_port'], self.options['listener_host'])

which is ugly and long. I always feel that writing something like:

uri = "http://%s:%s" % self.options['listener_port', 'listener_host']

should be possible but it's not valid (at least not in Python 2.7).

What's the "official" Pythonic way?

¿Fue útil?

Solución

If you use str.format instead of (more old-fashioned) % formatting, you can simply do:

"http://{0[listener_port]}:{0[listener_host]}".format(self.options)

In the more general case, you can get multiple values from a dict from a list of keys like:

values = [d[key] for key in keys]

and unpack using *, e.g.

"http://{0}:{1}".format(*(d[key] for key in keys))

but you can't unpack to % formatting.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top