Skip to content Skip to sidebar Skip to footer

Filtering Dictionary Based On Value In A Key

I would like to filter the dictionary that has 'hometown':'NY' [{'name': 'paul', 'age': '26', 'hometown': 'AU', 'gender': 'male'}, {'name': 'mei', 'age': '27', 'hometown': 'NY', 'g

Solution 1:

In [12]: a = [{'name': 'paul', 'age': '26', 'hometown': 'AU', 'gender': 'male'},
    ...:
    ...: {'name': 'mei', 'age': '27', 'hometown': 'NY', 'gender': 'female'},
    ...: {'name': 'smith', 'age': '14', 'hometown': 'NY', 'gender': 'male'},
    ...: {'name': 'raj', 'age': '13', 'hometown': 'IND', 'gender': 'male'}]

In [13]: [i for i in a if i["hometown"]=="NY"]
Out[13]:
[{'name': 'mei', 'age': '27', 'hometown': 'NY', 'gender': 'female'},
 {'name': 'smith', 'age': '14', 'hometown': 'NY', 'gender': 'male'}]

Solution 2:

You can try this:

result = [{'name': 'paul', 'age': '26', 'hometown': 'AU', 'gender': 'male'},
{'name': 'mei', 'age': '27', 'hometown': 'NY', 'gender': 'female'},
{'name': 'smith', 'age': '14', 'hometown': 'NY', 'gender': 'male'},
{'name': 'raj', 'age': '13', 'hometown': 'IND', 'gender': 'male'}]

a=[]
for i, testin enumerate(result):
    for key,value in test.items():
        if key == 'hometown':
            if'NY'in value:
                a.append(result[i])
print(a)

output:

[{'name': 'mei', 'age': '27', 'hometown': 'NY', 'gender': 'female'}, {'name': 'smith', 'age': '14', 'hometown': 'NY', 'gender': 'male'}]

Post a Comment for "Filtering Dictionary Based On Value In A Key"