Unicoded string key error in python dict
<p>I have such a code:</p>

<pre><code>corpus_file = codecs.open("corpus_en-tr.txt", encoding="utf-8").readlines()

corpus = []
for a in range(0, len(corpus_file), 2):
     corpus.append({'src': corpus_file[a].rstrip(), 'tgt': corpus_file[a+1].rstrip()})

params = {}

for sentencePair in corpus:
     for tgtWord in sentencePair['tgt']:
          for srcWord in sentencePair['src']:
               params[srcWord][tgtWord] = 1.0
</code></pre>

<p>Basically I am trying to create a dictionary of dictionary of float. But I get the following error:</p>

<pre><code>Traceback (most recent call last):
  File "initial_guess.py", line 15, in &lt;module&gt;
    params[srcWord][tgtWord] = 1.0
KeyError: u'A'
</code></pre>

<p><a href="http://stackoverflow.com/questions/36607145/utf-8-string-as-key-in-dictionary-causes-keyerror">UTF-8 string as key in dictionary causes KeyError</a></p>

<p>I checked the case above, but it doesn't help.</p>

<p>Basically I don't understand why unicoded string 'A' is not allowed in python to be a key value? Is there any way to fix it?  </p>

<p>Your <code>params</code> dict is empty.</p>

<p>You can use tree for that:</p>

<pre><code>from collections import defaultdict

def tree():
    return defaultdict(tree)

params = tree()
params['any']['keys']['you']['want'] = 1.0
</code></pre>

<p>Or a simpler <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> case without <code>tree</code>:</p>

<pre><code>from collections import defaultdict

params = defaultdict(dict)

for sentencePair in corpus:
    for tgtWord in sentencePair['tgt']:
        for srcWord in sentencePair['src']:
               params[srcWord][tgtWord] = 1.0
</code></pre>

<p>If you don't want to add anything like that, then just try to add dict to <code>params</code> on every iteration:</p>

<pre><code>params = {}

for sentencePair in corpus:
    for srcWord in sentencePair['src']:
        params.setdefault(srcWord, {})
        for tgtWord in sentencePair['tgt']:  
               params[srcWord][tgtWord] = 1.0
</code></pre>

<p>Please note, that I've changed the order of <code>for</code> loops, because you need to know <code>srcWord</code> first.</p>

<p>Otherwise you need to check key existence too often:</p>

<pre><code>params = {}

for sentencePair in corpus:
    for tgtWord in sentencePair['tgt']:
        for srcWord in sentencePair['src']:
            params.setdefault(srcWord, {})[tgtWord] = 1.0
</code></pre>

python dictionary unicode