+ 1

Why is the output 3 and not 4 in my script in the description?

I have a question. What's the output of this code: pairs = {1: "apple", "orange": [2, 3, 4], True: False, 12: "True", } print(len(pairs)) The playground console output was three, but there are four keys: 1, "orange", "True" and 12. Maybe I am wrong. But even ChatGBT gave me the answer 4 😂🤔😂

23rd Jul 2023, 8:50 PM
Waseem Esayed
Waseem Esayed - avatar
7 odpowiedzi
+ 8
Waseem Esayed, more than one entry per key is not allowed. This means that duplicate keys are not allowed. If duplicate keys are encountered during assignment, the last assignment wins. In your case, the True key belongs to the boolean class, which inherits from the int class and has the value 1. Therefore, the first value of the key 1 is overwritten to False, so the length of the dictionary is 3.
24th Jul 2023, 12:13 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 4
Waseem Esayed observed in this code how the boolean acts and why 3 not 4 but in the second half how 4 is reached https://code.sololearn.com/c5h0WShEXCrG/?ref=app
23rd Jul 2023, 9:40 PM
BroFar
BroFar - avatar
+ 2
Print the dictionary and observe which keys it has.
23rd Jul 2023, 9:01 PM
Lisa
Lisa - avatar
+ 2
Thanks for helping me guys ❤
25th Jul 2023, 12:39 AM
Waseem Esayed
Waseem Esayed - avatar
+ 1
the keys should be unique. But you have 1 and True and thats not unique print(pairs.get(True)) print(pairs.get(1)) for botjh you get the value „False“, so the first key:value pair will be ignored. and so the len is 3.
24th Jul 2023, 4:30 AM
Angela
Angela - avatar
+ 1
ChatGPT is not trained enough for that question 🤷‍♂️ so we humans have to learn further, then we can train ChatGPT 😃.
24th Jul 2023, 4:40 AM
Angela
Angela - avatar
+ 1
Wow: ChatGPT is learning fast, now it already know that 1 and True are the same like 0 and False. pairs = {0: "apple", "red": [2, 3, 4], False: False, 12: "true"} ``` The keys are `0`, `"red"`, `False`, and `12`. Python considers `0` and `False` as equivalent keys in a dictionary due to their truthiness in a boolean context. As a result, the dictionary `pairs` will have a length of 3, not 4. Since `0` and `False` are considered the same key due to their truthiness, one of them will overwrite the other in the dictionary, resulting in a length of 3 for the `pairs` dictionary.
24th Jul 2023, 4:58 AM
Angela
Angela - avatar