Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - Most efficient way to search in list of dicts

I have the following list of dicts.

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

Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some 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. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Doing a quick timeit on the functions show that using filter seems to be the fastest of all the methods

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

1000000 loops, best of 3: 263 ns per loop

  • Using next produces a time of 731ns
  • Using the search method produces a time of 361ns
  • And lastly the seach_dictionaries uses 811ns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...