I am importing multiple dictionaries from a .txt file into my python file and then I have to search for a key ('name') in all of the dictionaries but my code only searches in the first dictionary and gives the results accordingly. I want to know if there is an easy way to handle this situation. Immediate help would be appreciated. The current code and the data in .txt file is presented below:
elif option == 's':
if 'name' in open('data.txt').read():
sea = input ("Type a menu item name to search for: ")
file = open('data.txt', 'r')
data = json.load(file)
for index, line in enumerate(data):
if sea.lower() in line['name'].lower():
print (index, line['name'])
print ('No such item exist')
print ("The list is empty")
The problem is that you've made your first loop iteration to be the entire world: it looks at the first item in the list, reports success or failure on that search alone, and then calls the main program recursively (which is poor program construction, as well).
Try something with logic on this order:
found = False for index, line in enumerate(data): if sea.lower() in line['name'].lower(): print (index, line['name']) found = True if not Found: print ('No such item exists')
Finally, rather than calling main() wrap this in a while loop that tests the program's termination condition.