+ 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?
15 Respuestas
- 5
Hridoy
+ 5
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'} ?
+ 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
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
Hi
- 2
āĻāĻŽāĻžāĻ° āĻāĻŋāĻĄāĻŋāĻāĻ¤ā§ āĻ˛āĻžāĻāĻ āĻāĻŽā§āĻ¨ā§āĻ āĻļā§āĻ¯āĻŧāĻžāĻ° āĻ¸āĻŦāĻžāĻ āĻāĻ°āĻŦā§āĻ¨ āĻ¨āĻ¤ā§āĻ¨ āĻāĻŋāĻĄāĻŋāĻ āĻāĻĒāĻ˛ā§āĻĄ āĻāĻ°āĻž āĻšāĻŦā§
- 2
Hlo
- 2
Kon
- 3
Hlo
- 3
ŲØĢØĩØĩ