I have the following problem: I have a defaultdict called word_count containing words and the number how often they occur. I get this by counting the reply of the Google Speech API. However, this API gives me back things like '\303\266' for the German letter 'ö'. Now I want to go through this dict, test if one of these things shown above is there and replace it with the right thing like this:
Filling the defaultdict:
word_count = defaultdict(int)
for line in fileinput.input([file]):
line = line.strip()
words = line.split()
for word in words:
word_count[word] += 1
So far it works fine, I can print the dict and it gets me the words with the number.
Now replacing the key:
for key,val in word_count:
if '\\303\\266' in key:
new = key.replace('\\303\\266', 'ö')
word_count[new] = word_count.pop(key)
Now this does not work, I guess because I cannot pop(key) as it expects an integer. How else would I do this? I tried several approaches, but nothing seems to work here.
Any help would be greatly appreciated!
Solution:
Turns out this was my fault, as I sorted the dict and thereby turned it to a list of tuples. Thanks to everyone who helped me figure this out!
From the discussions get to know that you are treating with list of tuple instead of dict
. So list.pop
always expect a integer that's why you getting an error.
TypeError: list indices must be integers, not str
And dict
expect it's key. So here you have to convert the input like dict
or pop up from list with using it's index.