Search code examples
pythondictionarykeyerror

KeyError, even though key is in dictionary? What am I doing wrong?


Ok, so I am getting a key error, and I've narrowed it down to this function here:

    def find_coexistance(D, query):
        '''(dict,str)->list
        Description: outputs locations of words in a test based on query
        Precondition: D is a dictionary and query is a string
        '''
        query = query.split(" ")

        if (len(query) == 1):
            return D[str(query)]
        else:
            return D.intersection(query)
##############################
# main
##############################
file=open_file()
d=read_file(file)
query=input("Enter one or more words separated by spaces, or 'q' to quit:").strip().lower()
a = find_coexistance(d, query)
print (a)

This is the following output I receive:

Traceback (most recent call last):
File "C:\Users\hrith\Documents\ITI work\A5_300069290\a5_part1_300069290.py", 
line 135, in <module>
a = find_coexistance(d, query)
File "C:\Users\hrith\Documents\ITI work\A5_300069290\a5_part1_300069290.py", 
line 122, in find_coexistance
return D[str(query)]
KeyError: "['this']"

and this is what is inside the dictionary:

d = {'this': {1, 2, 3, 4}, 'is': {1, 2, 3, 4}, 'man': {1, 2}, 'also': {2, 
    4}, 'woman': {3, 4}}

and if I check if 'this' is in the dictionary, I get:

>>>'this' in d
True

So what am I doing wrong??????


Solution

  • When you use split() on a string, it always returns a list. So "foo bar".split(" ") gives ["foo", "bar" ]. BUT "foo".split(" ") gives a 1-element list ["foo"].

    The code is using a list of strings as the dictionary index, not a plain string.

    def find_coexistance(D, query):
        query = query.split(" ")
    
        if (len(query) == 1):
            return D[str(query)]   # <-- HERE
        else:
            return D.intersection(query)
    

    It's a simple fix, take the first element of the split.

    def find_coexistance(D, query):
        query = query.split(" ")
    
        if (len(query) == 1):
            return D[query[0]]   # <-- HERE
        else:
            return D.intersection(query)