+ 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 😂🤔😂
7 Réponses
+ 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.
+ 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
+ 2
Print the dictionary and observe which keys it has.
+ 2
Thanks for helping me guys ❤
+ 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.
+ 1
ChatGPT is not trained enough for that question 🤷♂️ so we humans have to learn further, then we can train ChatGPT 😃.
+ 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.