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>You can just use <code>setdefault</code>:</p>

<p>Replace
</p>

<pre class="lang-python prettyprint-override"><code>params[srcWord][tgtWord] = 1.0
</code></pre>

<p>with</p>

<pre class="lang-python prettyprint-override"><code>params.setdefault(srcWord, {})[tgtWord] = 1.0
</code></pre>

python dictionary unicode