Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

Assume I have this:

{"name": "Tom", "age": 10}, 

{"name": "Mark", "age": 5}, 

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

]

and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7}

How to achieve this?

2 Answers

0 votes
by (106k points)

If you want to search from Python list of dictionaries then you can use a generator expression below is the code for that shows how to use the generator expression:-

Generator Expression:-

A generator expression is a high performance, memory efficient and generalization of list comprehensions.

dicts = [ 

{"name": "Tom", "age": 10}, 

{"name": "Mark", "age": 5}, 

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

]

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

image

0 votes
by (20.3k points)

For this code:

people = [

{'name': "Tom", 'age': 10},

{'name': "Mark", 'age': 5},

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

]

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

The output will be returned as a list in Python 2 like this:

[{'age': 7, 'name': 'Pam'}]

Note that In Python 3, a filter object will be returned. So, the python3 solution will be like this:

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

Browse Categories

...