tarp20
tarp20

Reputation: 695

How to check if there is a value?

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

Answers (2)

vsrukshan
vsrukshan

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

adir abargil
adir abargil

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

Related Questions