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>By doing <code>{-1: '-', 1: '', my_value: str(my_value)}</code>, you overwrite the <code>-1</code> or <code>1</code> entries if <code>my_value</code> is <code>-1</code> or <code>1</code> respectively. Instead, you can use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>dict.get</code> with a default value</a>:</p>

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

python python-3.x dictionary