Reputation: 695
I have List of dictionaries:
[{
'Make_Name': 'HONDA',
'Model_Name': 'Accord'},
{
'Make_Name': 'HONDA',
'Model_Name': 'Civic'},
....................
{
'Make_Name': 'HONDA',
'Model_Name': 'Pilot'},
How to check if a certain Model_Name is in this list.
Accord --> True
ajejhc-->False
Upvotes: 1
Views: 63
Reputation: 130
You can use a for loop with dict().values() method as below code
a_list = [{
'Make_Name': 'HONDA',
'Model_Name': 'Accord'},
{
'Make_Name': 'HONDA',
'Model_Name': 'Civic'},
{
'Make_Name': 'Accord',
'Model_Name': 'Pilot'}]
for dic in a_list:
print('Accord' == dic['Model_Name'])
#or
#return 'Accord' == dic['Model_Name']
Upvotes: 1
Reputation: 5745
assuming you store the wanted name as car_model
you can do this:
print(car_model in [v['Model_Name'] for v in list_of_dicts])
>>> True # or False
there is a better option which is also more performant because it avoids iterating when one condition is met..
any(car_model == v['Model_Name'] for v in list_of_dicts)
>>> True # or False
note this i removed the [
]
and now it is a generator so we avoid creating the whole list..
Upvotes: 3