Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError on If-Condition in dictionary Python

I have this problem:

I hav this code that is trying to count bigrams in a text file. An if statement checks wether the tuple is in a dictionary. If it is, the value (counter) is one-upped. If it doesn't exist, the code shoud create a key-value pair with the tuple as key and the value 1.

for i in range(len(temp_list)-1):
    temp_tuple=(temp_list[i], temp_list[i+1])
    if bigramdict[temp_tuple] in bigramdict:
        bigramdict[temp_tuple] = bigramdict[temp_tuple]+1
    else:
        bigramdict[temp_tuple] = 1

However, whenever I run the code, it throws a KeyError on the very first tuple. As far as I understand, KeyError gets thrown when a key in dict doesn't exist, which is the case here. That's why I have the if statement to see if there is a key. Normally, the program should see that there is no key and go to the else to create one.

However, it gets stuck on the if and complains about the missing key.

Why does it not recognize that this is a conditional statement?

Pls help.

like image 826
PyDev Avatar asked Sep 20 '20 18:09

PyDev


People also ask

How do I fix KeyError in Python?

How to Fix the KeyError in Python Using the in Keyword. We can use the in keyword to check if an item exists in a dictionary. Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.

What is KeyError in Python dictionary?

What is Python KeyError Exception? Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.

How do I fix KeyError 0 Python with a dictionary?

The Python "KeyError: 0" exception is caused when we try to access a 0 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.


2 Answers

What you were trying to do was

if temp_tuple in bigramdict:

instead of

if bigramdict[temp_tuple] in bigramdict:
like image 77
Captain Trojan Avatar answered Sep 20 '22 00:09

Captain Trojan


For a more Pythonic solution, you can pair adjacent items in temp_list by zipping it with itself but with an offset of 1, and use the dict.get method to default the value of a missing key to 0:

for temp_tuple in zip(temp_list, temp_list[1:]):
    bigramdict[temp_tuple] = bigramdict.get(temp_tuple, 0) + 1
like image 35
blhsing Avatar answered Sep 20 '22 00:09

blhsing