Rename defaultdict key in Python
<p>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:</p>

<p>Filling the defaultdict:</p>

<pre><code>word_count = defaultdict(int)
for line in fileinput.input([file]):
    line = line.strip()
    words = line.split()
    for word in words:
        word_count[word] += 1
</code></pre>

<p>So far it works fine, I can print the dict and it gets me the words with the number.</p>

<p>Now replacing the key:</p>

<pre><code>for key,val in word_count:
    if '\\303\\266' in key:
        new = key.replace('\\303\\266', 'Ã¶')
        word_count[new] = word_count.pop(key)
</code></pre>

<p>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.</p>

<p>Any help would be greatly appreciated!</p>

<p><strong>Solution:</strong></p>

<p>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!</p>

<p>From the discussions get to know that you are treating with list of tuple instead of <code>dict</code>. So <code>list.pop</code> always expect a integer that's why you getting an error.</p>

<pre><code>TypeError: list indices must be integers, not str
</code></pre>

<p>And <code>dict</code> expect it's key. So here you have to convert the input like <code>dict</code> or pop up from list with using it's index.</p>

python defaultdict google-speech-api