我有一份消费者名单:
API_CONSUMERS = [{'name': 'localhost',
'host': '127.0.0.1:5000',
'api_key': 'Ahth2ea5Ohngoop5'},
{'name': 'localhost2',
'host': '127.0.0.1:5001',
'api_key': 'Ahth2ea5Ohngoop6'}]
我有一个主变量:
host = '127.0.0.1:5000'
我想:
api_key
以在其他地方使用。最初我正在检查这样的主机值:
if not any(consumer['host'] == host for consumer in API_CONSUMERS):
#do something
然后意识到要检索api_key
无论如何我必须循环遍历每个消费者,所以不妨将两者结合起来:
for consumer_info in API_CONSUMERS:
if consumer_info['host'] == host:
consumer = consumer_info
if not consumer:
#do something
最好的方法是什么?我觉得我所做的不是“pythonic”。
解决方案
try:
api_key = next(d['api_key'] for d in consumers if d['host'] == host)
except StopIteration:
#do something
答案 0 :(得分:3)
>>> next(consumer['api_key'] for consumer in API_CONSUMERS if consumer['host'] == host)
'Ahth2ea5Ohngoop5'
不要忘记捕获未找到值时将引发的异常。
答案 1 :(得分:3)
api_key = next(d['api_key'] for d in API_CONSUMERS if d['host'] == host)
一次性获取密钥,如果列表中没有此类主机,则会引发异常。
修改强>
正如sr2222所指出的,如果主机不是唯一的,OP的代码和我的代码的语义是不同的。因此,要获得最后一个主机,可以执行以下操作:
api_key = [d['api_key'] for d in API_CONSUMERS if d['host'] == host][-1]
或者只保留整个列表。 (如果列表为空,仍会引发异常)。
答案 2 :(得分:0)
一个(也许)更多python构造将用于 - else:
for consumer_info in API_CONSUMERS:
if consumer_info['host'] == host:
consumer = consumer_info
#do stuff with consumer
break
else:
#clause if no consumer
答案 3 :(得分:0)
如果你想拥有最有效的搜索过程,你应该使用字典数据结构。因为它的复杂性(增长的顺序)是最少的。你可以这样做:
API_CONSUMERS = {'127.0.0.1:5000':{'name':'localhost','api_key': 'Ahth2ea5Ohngoop5'},
'127.0.0.1:5001': {'name':'localhost2','api_key': 'Ahth2ea5Ohngoop6'}}
如果你想搜索使用:
if host in API_CONSUMERS.keys():
return API_CONSUMERS[host]['api_key']