What is the most efficient way to access the value of a sibling dictionary in python?

In Python, I have a list of dictionaries that look 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 is the most efficient way to get the domain value for an item?

+3
source share
5 answers

You can use list comprehension :

domains = [matching['domain'] for matching in matchings if matching['id'] == the_id]

What follows the standard format format:

resulting_list = [item_to_return for item in items if condition]

And basically encapsulates all of the following functions:

domains = []
for matching in matchings:
    if matching['id'] == the_id:
        domains.append(matching['domain'])

All of these features are presented on a single line using lists.

+5
source

I would restructure matchings.

from collections import defaultdict
matchings_ix= defaultdict(list)
for m in matchings:
    matchings_ix[m['id']].append( m )

Now the most effective search

matchings_ix[ d ]
+2

, , . , Python, , , ++ STL

[d["domain"] for d in matchings if d["id"] == "someid3"]
+1

, , - , - . @Soviut - : , , . , - , bisect.

0

I really like to use filter in a similar situation. It executes the function and repeats and returns a list of elements where the function returns True (in Python 3.x it returns an iterator).

>>> filter(lambda x: x['id'] == 'someid3', matchings)
<<< [{'domain': 'somedomain3.com', 'id': 'someid3'}]

You can get a list of all domains using list comprehension:

>>> [x['domain'] for x in filter(lambda x: x['id'] == 'someid3', matchings)]
<<< ['somedomain3.com']
0
source

All Articles