Home >Backend Development >Python Tutorial >How to Efficiently Find Specific Key-Value Pairs in a List of Python Dictionaries?

How to Efficiently Find Specific Key-Value Pairs in a List of Python Dictionaries?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 18:42:12991browse

How to Efficiently Find Specific Key-Value Pairs in a List of Python Dictionaries?

Searching for Specific Dictionnaire Key-Values in Python

Given a list of dictionaries, it is common to search for specific key-values to retrieve the corresponding dictionary. For instance, consider the following list:

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

To find the dictionary with the name "Pam", we can use a generator expression:

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

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

The next() function returns the first item in the generator, which is the dictionary with the name "Pam". Using a generator expression allows for efficient iteration without storing all the results in memory.

For cases where the item may not exist, we can provide a default value by using the next() function with a parameter:

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

Alternatively, we can find the index of the matching item using enumeration:

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

The above is the detailed content of How to Efficiently Find Specific Key-Value Pairs in a List of Python Dictionaries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn