Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to access sibling dictionary value in a Python dict?

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?

like image 277
Nick Sergeant Avatar asked Jan 24 '23 22:01

Nick Sergeant


2 Answers

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.

like image 109
Soviut Avatar answered Feb 06 '23 15:02

Soviut


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 ]
like image 34
S.Lott Avatar answered Feb 06 '23 14:02

S.Lott