+ 1
Why is Python behaving wierd here?
I just came through Dictionary get() method in python. I was just playing around and I noticed: Input: nums = { 1: 'one', 2: 'two' } print(nums.get(1)) print(nums.get(2)) Output: one two It produced a correct output above whereas when I add another key-value pair, it behaves wierd: Input: nums = { 1: 'one', 2: 'two', True: False } print(nums.get(1)) print(nums.get(2)) Output: False 2 Can I know the reason for the wierd result. I am unable to get explanation anywhere
1 Resposta
+ 6
Actually, a Dictionary key should be a hashable object and it's using its hash value. True, 1, 1.0 all have same hash value which is 1.
https://docs.python.org/3/library/functions.html#hasattr
(Here 1:'one', True: False)
By default, we cannot have multiple keys with the same name in dictionaries. Therefore python overrides the value to the last assigned value (False in this case).
If you want to get a different output, you may change the key True to 3 or any other value.