0

I have to take input from the user in the form of strings and then have to search for it in a .txt file which is in JSON format. If the text matches, X has to be done otherwise Y. For example if the user enters 'mac' my code should display the complete name(s) of the terms which contains the search term 'mac'.

My JSON file has currently Big Mac as an item and when I search for 'mac' it shows nothing, whereas, it has to display me (0 Big Mac). 0 is the index number which is also required.

  if option == 's':
        if 'name' in open('data.txt').read():
            sea = input ("Type a menu item name to search for: ")
            with open ('data.txt', 'r') as data_file:
                data = json.load(data_file)
            for line in data:
                if sea in line:
                    print (data[index]['name'])
                else:
                    print ('No such item exist')
        else:
            print ("The list is empty")
            main()

I have applied a number of solutions but none works.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Talha Farrukh
  • 21
  • 2
  • 8

1 Answers1

0

See How to search if dictionary value contains certain string with Python.

Since you know you are looking for the string within the value stored against the 'name' key, you can just change:

if sea in line

to:

if sea in line['name']

(or if sea in line.get('name') if there is a risk that one of your dictionaries might not have a 'name' key).

However, you're attempting to use index without having set that up anywhere. If you need to keep track of where you are in the list, you'd be better off using enumerate:

for index, line in enumerate(data):
    if sea.lower() in line['name'].lower():
        print ((index, line['name']))

If you want 'm' to match 'Big Mac' then you will need to do case-insensitive matching ('m' is not the same as 'M'). See edit above, which converts all strings to lower case before comparing.

Community
  • 1
  • 1
user3468054
  • 610
  • 4
  • 11
  • 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 sub_dict in data: if sea in sub_dict['name']: print (sub_dict['name']) main() else: main() else: print ("The list is empty") main() – Talha Farrukh Oct 23 '16 at 09:04
  • It is also working partially, not for the second or third item in the dictionary. And doesn't matches if lower case letter is entered – Talha Farrukh Oct 23 '16 at 09:08
  • @TalhaFarrukh if you enter 'whopper' (to search for the second dictionary) then you'll end up going through your `else: main()` clause, and stopping searching through the list. – user3468054 Oct 23 '16 at 09:15
  • What should I do then? – Talha Farrukh Oct 23 '16 at 10:00
  • It resolves the problem of lower and upper case characters but still didn't search for other items in the dictionary – Talha Farrukh Oct 24 '16 at 02:14