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
Release: 2024-12-06 18:42:12
Original
1007 people have browsed it

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 }
]
Copy after login

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")
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template