我有一个消费者列表:
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'
我想:
- 检查host是否在API_CONSUMERS列表中的值中,然后
- 如果主机存在,检索
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
请您参考如下方法:
>>> next(consumer['api_key'] for consumer in API_CONSUMERS if consumer['host'] == host)
'Ahth2ea5Ohngoop5'
如果找不到值,不要忘记捕获将引发的异常。
