+ 1
len() limitation? I am trying to use len() in dictionary. While it works on certain integers key (12), it doesn't work on others
6 ответов
+ 3
Amd
Print pairs you will see pairs has only 3 keys
print (pairs)
+ 2
Amd notice that len(pairs) is 3, but the dictionary seemingly should have 4 elements.
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
12: "True",
}
Do you know why it says 3?
It is because one of the keys is defined twice. True has a value of 1, so 1:"apple" gets replaced by 1:False. If you redefine the value for a given key, the dictionary stores only the last value that it was given.
Now you can review the program output and understand why you get that result.
+ 1
Have a look at the error message, it says:
object of type bool has no length
False, for example, has no length. "False" as a string, for example, has a length (number of characters)
+ 1
That's exactly the error message you get from line 13 (you can see it from the error message.
get() method gets the value associated with the key, not the key itself.
12 is the key for the string value "True" which has length 4 due to 4 characters.
0
Thanks Lisa. I am referring to Line 13 and 14. While lines 11 and 12 runs which are integers, lines 13 and 14 do not
0
12 has a length which is 4 string characters
Also, 1 has a length which is 5 string characters but the length is not returned.