+9

Why does this code print {True: 'maybe'} ?

https://code.sololearn.com/cFBFAySD5LuJ/?ref=app Why is the first key associated with the last value?

12/6/2019 11:19:11 PM

Sonic

15 Answers

New Answer

-5

+5

Petr OK, thanks.

+4

Sonic Try it easier: dict={1:'no',1.0:'maybe'} print(dict) the result will help you understand the secret of this dict

+4

Petr thanks, so the keys are effectively the same as True is 1? The last value overrides the previous values but why don't the keys specified later override the first instance of True? E.g. why is the answer not {1.0: 'maybe'} ?

+4

Sonic about the keys, I agree with you. Regarding the second, assignment by a new key overwrites it. true = 1, i.e. the first key is displayed as in the dictionary, and the value is the last assigned to it by this key value

+4

To understand, it is necessary to know how Python build dicts. In the first example, it will create the dict in the order specified : first 'True : "yes"'. At this point, when python see '1 : "no"', the key True is already created. And that changes all. In python, for instance, you can write both : while 1 or while True ; that means that Python evaluates the value 1 as True, even 1.0. So, it can't create a new key since key 'True' already exists.

+4

If the hash value of two objects is the same and they check as equal, they'll be considered as one and the same thing for dict purposes. So if one of them is already in there, it will not be overwritten, but the value will just be updated. Run (and meditate over) this: class StrangeThing: def __repr__(self): return '^_^' def __hash__(self): return 1 def __eq__(self, other): return True d = {} for obj in StrangeThing(), 1, 1.0, True: print(hash(obj)) d[obj] = 'x' print(d)

+2

I got this from a challenge question. Unsure about the rule here.

-1

Напишу хоть что то на своем языке

-2

-2

আমার ভিডিওতে লাইক কমেন্ট শেয়ার সবাই করবেন নতুন ভিডিও আপলোড করা হবে

-2

-2

-3

-3