How to efficiently search dictionaries in Python?

How to Search a List of Dictionaries in Python?

Given the following list of dictionaries:

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

How can I search by name == "Pam" to retrieve the corresponding dictionary:

{"name": "Pam", "age": 7}

How can I perform this search efficiently in a list of dictionaries Python?

Hey All!

Using a Loop When working with a list of dictionaries in Python, one approach is to use a loop. You iterate through the list and check for the specific key-value pair you’re looking for. Here’s an example:

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

result = None
for item in data:
    if item['name'] == "Pam":
        result = item
        break
print(result)

This approach is straightforward and easy to understand, especially for beginners.

Hello Everyone,

Here is the Answer:-

Building on @ian-partridge’ssolution, you can make it more concise by using list comprehension. When working with a list of dictionaries in Python, list comprehension allows for a cleaner way to filter and find the matching dictionary. Here’s how:

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

result = [item for item in data if item['name'] == "Pam"]
print(result[0] if result else None)

This method creates a new list containing the matching dictionaries, and you can access the first match. It’s an elegant approach for filtering.

  • @ian-partridge’s solution is great, but what if you want to stop searching as soon as you find the first match? The next() function with a generator expression is perfect for this.* This approach is highly efficient for searching in a list of dictionaries in Python, especially when you only need the first match:
data = [
  {"name": "Tom", "age": 10},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7}
]

result = next((item for item in data if item['name'] == "Pam"), None)
print(result)

Using next() with a generator expression ensures that the iteration stops as soon as a match is found, which is particularly useful when dealing with large datasets.