Weird dictionary construct - duplicate keys
<p>I needed to write a function that 'maps' -1 to just '-', 1 to '' (yes, nothing) and every other value to a string representation of itself. Instead of using <code>if</code> statements i though i would do it with a dictionary like so:</p>

<pre><code>def adj(my_value):
    return {-1: '-', 1: '', my_value: str(my_value)}[my_value]
</code></pre>

<p>And then it hit me, this dictionary allows duplicate keys and behaves as follows:</p>

<pre><code>for x in [-1, 1, 4]:
    print(adj(x))
# -&gt; -1
# -&gt; 1
# -&gt; 4
</code></pre>

<p>I did run it multiple times to make sure the <code>print()</code> was not "random" since dicts are not ordered but i consistently get this output.</p>

<hr>

<p>Now this is definitely not the behavior i was going for and in no way can such a construct be trusted but does anyone know why such a thing is even allowed since duplicate keys aren't? How is the calculation performed?</p>

<p>Quoting the <a href="https://docs.python.org/3/reference/expressions.html#dictionary-displays" rel="nofollow">Python docs</a>:</p>

<blockquote>
  <p>If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. <strong>This means that you can specify the same key multiple times in the key/datum list, and the final dictionaryâs value for that key will be the last one given.</strong></p>
</blockquote>

<p>It's not undefined behavior, it's as if you created an empty dictionary and set each key, one by one. You can fix your code by just shuffling the order around:</p>

<pre><code>def adj(my_value):
    return {my_value: str(my_value), -1: '-', 1: ''}[my_value]
</code></pre>

<p>Other people might find this approach hard to read, though, so you may want to use <code>dict.get</code>'s default value, as the other answers have shown.</p>

<p>Your question was recently asked on the <a href="https://mail.python.org/pipermail/python-ideas/2016-May/040042.html" rel="nofollow">Python mailing list</a> (in an easier to read format <a href="https://code.activestate.com/lists/python-ideas/39826/" rel="nofollow">here</a>).</p>

python python-3.x dictionary