3

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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
  • 2
    @Aran-Fey but the 1.0 part isn't addressed there right? – Jean-François Fabre Sep 19 '18 at 09:14
  • 1
    @Jean-FrançoisFabre No, but is that really necessary? The answers do a good enough job explaining that sets (and dicts) eliminate items that hash and compare equal. – Aran-Fey Sep 19 '18 at 09:15
  • 1
    I'd say it's a necessary duplicate, then. Because of the confusion that could exist because `bool` is a subclass of `int`, while `float` isn't.. yes this is a duplicate, but I'm not going to fight to delete it. Useful dupe. damn I edited _after_ closure :) – Jean-François Fabre Sep 19 '18 at 09:18

1 Answers1

5

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).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111