KeyError on If-Condition in dictionary Python
Asked Answered
S

2

7

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.

Shondrashone answered 20/9, 2020 at 18:46 Comment(2)
Does this answer your question? I'm getting Key error in pythonPhysiotherapy
bigramdict = Counter(zip(temp_list, temp_list[1:])). (Not the most efficient way to do this, but the shortest and easiest to understand.)Adaiha
A
9

What you were trying to do was

if temp_tuple in bigramdict:

instead of

if bigramdict[temp_tuple] in bigramdict:
Adamok answered 20/9, 2020 at 18:51 Comment(2)
OMG thanks so much, you're right! I had a similar function, where I used an iterator, and I sort-of copied it over, not realizing my mistake. Thank you very much for the quick answer!Shondrashone
@Shondrashone Gotcha ;)Adamok
D
2

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
Draughtboard answered 20/9, 2020 at 19:59 Comment(1)
Instead of the default get, you could also use a defaultdict; from collections import defaultdict // bigramdict = defaultdict(int) // bigramdict[temp_tuple] += 1.Indra

© 2022 - 2024 — McMap. All rights reserved.