In Python, I've got a list of dictionaries that looks like this:
matchings = [
{'id': 'someid1', 'domain': 'somedomain1.com'},
{'id': 'someid2', 'domain': 'somedomain2.com'},
{'id': 'someid3', 'domain': 'somedomain3.com'}
]
and, I have a variable:
the_id = 'someid3'
What's the most efficient way to retrieve the domain value of the item?
You can use a list comprehension:
domains = [matching['domain'] for matching in matchings if matching['id'] == the_id]
Which follows the format standard format of:
resulting_list = [item_to_return for item in items if condition]
And basically encapsulates all the following functionality:
domains = []
for matching in matchings:
if matching['id'] == the_id:
domains.append(matching['domain'])
All that functionality is represented in a single line using list comprehensions.
I'd restructure matchings
.
from collections import defaultdict
matchings_ix= defaultdict(list)
for m in matchings:
matchings_ix[m['id']].append( m )
Now the most efficient lookup is
matchings_ix[ d ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With