问题描述
我经常发现自己在做这样的事情:
有没有一个简单,可读和Pythonic的方法来从dict中提取特定的值, / p>
uri =http://%s:%s%(self.options ['listener_port'],self.options ['listener_host'])
这是丑陋而长久的。我总是觉得写的东西如下:
uri =http://%s:%s%self.options [ 'listener_port','listener_host']
应该是可能的,但它是无效的(至少不是在Python
什么是官方Pythonic方式?
如果您使用而不是(更老式)%
格式化,您可以简单地:
http:// {0 [listener_port]}:{0 [listener_host]}.format(self.options)
在更一般的情况下,您可以从 dict获得多个值
从键列表
如:
values = [ d [键]键入钥匙]
并使用 *
,例如
http:// {0}:{1} .format(*(键[key]键))
但你可以't unpack to %
formatting。
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?
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.
这篇关于具有键列表,从dict获取值的列表/元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!