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': 'blue', 'second_color': 'blue1'}]
conType = input('Enter main color: ')
color=input('Enter secondary color :')
conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')
valueDict={}
if conType:
valueDict[conType]=color
if conType1:
valueDict[conType1]=color1
print(valueDict)
for d in a:
for i,j in valueDict.items():
if d['main_color'] == i:
print('matched')
d['second_color'] = j
break
else:
print('no value')
print(a)
Below is the output When I tried to execute above code
Enter main color: red
Enter secondary color :black
Enter another main color: yellow
Enter another secondary color: white
{'red': 'black', 'yellow': 'white'}
matched
matched
no value
[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]
Issue here is 'no value' is getting printed. In my use case no value shouldn't be printed at all.
I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries. Please help.