+ 2

Please explain this to me.

I found this question in sololearn challenge Question: print({True: 'yes', 1: 'no', 1.0: 'maybe'}) Output: {True : 'maybe'} I don't understand why the output was this. Can someone explain it to me? Also is there any way to see explanations to answers for sololearn challenges?

10th Jun 2020, 6:56 AM
Deepa
7 Respuestas
+ 3
Dictionaties are mutable. That means, you can change it once you created. Again, if you assign a value to a key then again reassign another value to the same key, dics remember the second one. For example, mdic = {1: "1", 2: " 2", 1: "100"} mdic[3] = "3" print(mdic) output : {2: "2", 1: " 100", 3: "3"} Take a closer look at the code and see what happend. Now let's come to your question. bool() of anything except 0, empty (string, dic, list, tuple, set) and none are True. But integer 1 and float 1.0 is especially regarded as True. So, that is what haplend, print({True: 'yes', True: 'no', True: 'maybe')} Hope it helped.
10th Jun 2020, 7:09 AM
M Tamim
M Tamim - avatar
+ 4
XXX Roman J M Tamim You all are right about the fact that True, 1 and 1.0 are considered as an unique key in dictionaries but I think you might be wrong when you state that 1 and 1.0 are transformed to True(or one) and that the last key has higher precedence. Take a look at this and correct me if I'm wrong: https://code.sololearn.com/cUdWK5zB5Xyv/?ref=app
10th Jun 2020, 7:33 AM
Kevin ★
+ 2
1 & 1.0 are actually integer and float values for True (0 for False). So 1 is transformed to True in the dictionary. So the dictionary after 1 is transformed would be {True: 'yes', True: 'no', True: 'maybe'} As a dictionary cannot have duplicates, only the last definition of True will remain
10th Jun 2020, 7:05 AM
XXX
XXX - avatar
+ 1
Thank you!!
11th Jun 2020, 1:30 PM
Deepa
0
Since codes works with logic literally logic exists as when we print({True: 'yes', 1: 'no', 1.0: 'maybe'}) the result show {True : 'maybe'} because 1 is known as non float string and 1.0 is float string so the python works with both of the above value so the result is maybe! logically the value of both 1 and 1.0 is so it shows answer may be.
12th Jun 2020, 8:37 AM
Dipesh Gurung
Dipesh Gurung - avatar