Ev. Kounis Ev. Kounis - 3 months ago 10
Python Question

Weird dictionary construct - duplicate keys

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

if
statements i though i would do it with a dictionary like so:

def adj(my_value):
return {-1: '-', 1: '', my_value: str(my_value)}[my_value]


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

for x in [-1, 1, 4]:
print(adj(x))
# -> -1
# -> 1
# -> 4


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




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?

Answer

The dictionary you made doesn't have duplicate keys. The "duplicates" overwrote each other. It's just as if you had done this:

d = {}
d[1] = ''
d[1] = 1
print(d[1])

To demonstrate:

>>> def adj(my_value):
...     d = {-1: '-', 1: '', my_value: str(my_value)}
...     print(d)
...     return d[my_value]
...
>>> for x in [-1, 1, 4]:
...     print(adj(x))
...
{1: '', -1: '-1'}
-1
{1: '1', -1: '-'}
1
{1: '', 4: '4', -1: '-'}
4

BTW, you could write the function like this:

def adj(my_value)
    d = {-1: '-', 1: ''}
    return d.get(my_value, str(my_value))