The most effective way to search dicts

I have the following list of dicts.

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

What will be the most optimized way in terms of performance for searching the dicts list. Below are the various methods:

next((item for item in dicts if item["name"] == "Pam"), None)

OR

filter(lambda person: person['name'] == 'Pam', people)

OR

def search(name):
    for p in people:
        if p['name'] == name:
            return p

OR

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]

Any other method is also welcome. Thank.

+4
source share
2 answers

Running fast time on functions shows that using a filter is apparently the fastest of all methods

%timeit filter(lambda person: person['name'] == 'Pam', people)

1,000,000 cycles, best of 3: 263 ns per cycle

  • Using next creates a time of 731ns
  • Using the search method gives 361ns time
  • And finally, seach_dictionaries uses 811ns
+7
source

, ""

def search(name):
    for p in people:
        if p['name'] == name:
            return p

,

0

Source: https://habr.com/ru/post/1650758/


All Articles