+ 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.
7 Réponses
+ 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
+ 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.
+ 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
+ 3
Gordon thanks.
+ 3
HonFu I see. So I am wrong sorry
i just googled and found this
https://stackoverflow.com/questions/52402133/true-and-1-and-1-0-evaluated-to-be-same-in-JUMP_LINK__&&__python__&&__JUMP_LINK-dictionaries
which links to this
https://fengsp.github.io/blog/2017/3/python-dictionary/
+ 3
Thanks for the correction HonFu !