Skip to content Skip to sidebar Skip to footer

Having List Of Keys, Get List/tuple Of Values From Dict

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' % (

Solution 1:

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.

Post a Comment for "Having List Of Keys, Get List/tuple Of Values From Dict"