+ 2

Why is "Moon" the correct answer to the following question?

https://www.sololearn.com/post/176987/?ref=app Is it because 1 evaluates to True or because Python dictionaries are ordered with indexes starting from 1? I think it is the former.

16th Nov 2019, 11:58 PM
Sonic
Sonic - avatar
7 ответов
+ 2
Gordon, is that correct? It looks as if you are applying Javascript-rules to Python. There isn't a === in Python. What exactly == does, depends on how magic method __eq__ is implemented, which can be anything. class C: def __init__(self, n): self._n = n def __eq__(self, other): return id(self)!=id(other) print(C(2)==C(1)) # True And what keys of different types are regarded as one, should be more related to the magic method __hash__. class C: def __init__(self, n): self._n = n def __eq__(self, other): return 'whatever' def __hash__(self): return 1 d = {C(1): 0, C(2): 1} # Only 1 item
17th Nov 2019, 7:29 AM
HonFu
HonFu - avatar
+ 6
I think, True and 1 in dicts are treated as the same thing (aka only one of them as key) because they return the same hash value. So when you write d[1], you are accessing the already stored key True - in this case updating the associated value.
17th Nov 2019, 12:53 AM
HonFu
HonFu - avatar
+ 4
When you access value, it looks for the key in the dict with in. in is implemented not as === with strict type requirment but with == which is loose type requirement (type conversion occurs) https://code.sololearn.com/cB8JWWTLh1hd/?ref=app
17th Nov 2019, 1:57 AM
Gordon
Gordon - avatar
+ 3
Gordon thanks.
17th Nov 2019, 4:26 AM
Sonic
Sonic - avatar
+ 3
Thanks for the correction HonFu !
17th Nov 2019, 7:42 AM
Sonic
Sonic - avatar