I have a list of consumers:
API_CONSUMERS = [{'name': 'localhost',
'host': '127.0.0.1:5000',
'api_key': 'Ahth2ea5Ohngoop5'},
{'name': 'localhost2',
'host': '127.0.0.1:5001',
'api_key': 'Ahth2ea5Ohngoop6'}]
And I have a host variable:
host = '127.0.0.1:5000'
I want to:
- Check if host is in the values in the list of API_CONSUMERS, then
- If the host exists retrieve the
api_keyto use elsewhere.
Originally I was checking the host values like this:
if not any(consumer['host'] == host for consumer in API_CONSUMERS):
#do something
But then realised to retrieve the api_key I would have to loop through each consumer anyway, so might as well combine the two:
for consumer_info in API_CONSUMERS:
if consumer_info['host'] == host:
consumer = consumer_info
if not consumer:
#do something
What is the best way to do this? I feel like what I’m doing isn’t “pythonic”.
Solution
try:
api_key = next(d['api_key'] for d in consumers if d['host'] == host)
except StopIteration:
#do something
Don’t forget to catch the exception that will be raised if the value is not found.