pythondictionarylist-comprehensionlis

Python update list of dictionaries in a loop


I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

a = [{'main_color': 'red', 'second_color':'blue'},{'main_color': 'yellow', 'second_color':'green'},{'main_color': 'yellow', 'second_color':'blue'}]

print('Enter main color:')

conType=input()

for d in a:

    if d['main_color']==conType:
        print('matched')
        d['second_color']='bluetooth'
    else:
        print('no value')
print(a)

Issue here is if input is 'red' "no value" is getting printed twice and "matched" is printed once.

My use case is if input doesn't exist in list of dictionaries it should print "no value" only once. If input exists code should update next key with new value and print "matched" once.

I have been through other questions in stack overflow. I couldn't find answer to this scenario.

Please help


Solution

  • There's for .. else statement which you can use here:

    a = [{'main_color': 'red', 'second_color': 'blue'},
         {'main_color': 'yellow', 'second_color': 'green'},
         {'main_color': 'yellow', 'second_color': 'blue'}]
    
    conType = input('Enter main color: ')
    
    for d in a:
        if d['main_color'] == conType:
            print('matched')
            d['second_color'] = 'bluetooth'
            break
    else:
        print('no value')
    
    print(a)
    

    UPD.

    Sorry, I've missed that there's multiple objects with same main_color in the list (thanks, @HaleemurAli). In case if you don't need to break loop after matching you can't use for .. else statement, but you can use boolean flag. To check if string equals any of list of string you can membership test operator (in):

    a = [{'main_color': 'red', 'second_color': 'blue'},
         {'main_color': 'yellow', 'second_color': 'green'},
         {'main_color': 'blue', 'second_color': 'blue1'}]
    
    conType = input('Enter main color: ')
    conType1 = input('Enter another main color: ')
    
    b = [conType, conType1]
    matched = False
    for d in a:
        if d['main_color'] in b:
            print('matched')
            matched = True
            d['second_color'] = 'bluetooth'
    
    if not matched:
        print('no value')