-1

I am trying to create an interactive dictionary. The file data.json is where the definition of the words are stored. I expected the code to look up the definition of a word as entered by the user and print it out in the terminal.

import json

data = json.load(open("data.json", 'r'))
item = input("Enter word you are looking for: ")
data["%s", item]
print(data) 

However I keep getting the following error

Enter word you are looking for: rain
Traceback (most recent call last):
  File "C:\Users\Hassan\eclipse-workspace\FTS\src\FirstModule.py", line 10, in <module>
    data["%s", item]
KeyError: ('%s', 'rain')

I don't understand what is causing the error or how to fix it. Can someone please point out where I am making the mistake and suggest a possible solution.

Thanks in advance

SmithyB
  • 7
  • 2

2 Answers2

1

Just change data["%s", item] to data[item]. You have a string stored in the item variable, and you want that to be used as the index into your dictionary. That should resolve the key error.

alanc10n
  • 4,897
  • 7
  • 36
  • 41
0

That KeyError means just that the tuple ('%s', 'rain') does not exists in your dictionary.

Now you must ask yourself why would you want such object (that tuple) to be a key in your dictionary and why is not present yet.

Jorge Lavín
  • 937
  • 8
  • 22