True and 1 and 1.0 evaluated to be same in python dictionaries

Viewed 1486

Can anyone explain this behaviour of python dictionaries?

d = {}
d[True] = 'Magic'
d[1] = 'Cool'
d[1.0] = 'Hello'
print(d)

# {True: 'Hello'}

Why does it not print all the other (key, value) pairs?

Why does True, 1 and 1.0 is evaluated to be the same?

1 Answers

the hash of the 3 items 1, 1.0, True is the same (it equals 1). that's what python uses as the key for dictionaries if there are no collisions. and as 1 == 1.0 == True is also True there are no collisions.

here are more details about the old implementation of python dictionaries. the new implementation does things along those lines (but preserves the order).

Related