Talha Farrukh Talha Farrukh - 1 month ago 15
Python Question

Searching in a list of multiple dictionaries

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)
file.close()
for index, line in enumerate(data):
if sea.lower() in line['name'].lower():
print (index, line['name'])
main()
else:
print ('No such item exist')
main()
else:
print ("The list is empty")
main()


Dictionary:
[
{
"fat": 29,
"carbohydrates": 45,
"protein": 25,
"sodium": 1040,
"cholesterol": 75,
"calories": 540,
"name": "Big Mac"
},
{
"fat": 47,
"carbohydrates": 53,
"protein": 33,
"sodium": 1410,
"cholesterol": 100,
"calories": 760,
"name": "Whopper"
},
{
"fat": 80,
"carbohydrates": 50,
"protein": 650,
"calories": 45,
"cholesterol": 50,
"sodium": 50,
"name": "Icecream'"
}
]

Answer

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.