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>The dictionary you made doesn't have duplicate keys.  The "duplicates" overwrote each other. It's just as if you had done this:</p>

<pre><code>d = {}
d[1] = ''
d[1] = 1
print(d[1])
</code></pre>

<p>To demonstrate:</p>

<pre><code>&gt;&gt;&gt; def adj(my_value):
...     d = {-1: '-', 1: '', my_value: str(my_value)}
...     print(d)
...     return d[my_value]
...
&gt;&gt;&gt; for x in [-1, 1, 4]:
...     print(adj(x))
...
{1: '', -1: '-1'}
-1
{1: '1', -1: '-'}
1
{1: '', 4: '4', -1: '-'}
4
</code></pre>

<p>BTW, you could write the function like this:</p>

<pre><code>def adj(my_value)
    d = {-1: '-', 1: ''}
    return d.get(my_value, str(my_value))
</code></pre>

python python-3.x dictionary