+ 1

Default Value in Dictioary

pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get(1, "not in dictionary")) print(pairs.get("orange", "not in dictionary")) Expected Output: "apple" [2, 3, 4] Actual Output: False [2, 3, 4] Why is it coming False instead of apple?

31st Jan 2017, 8:06 PM
Anirban Bhattacherji
Anirban Bhattacherji - avatar
1 Resposta
+ 5
The problem is that in Python there is no real True/False value type, and 1 is strictly equal to True, so in reality, when you declare your array, you implicitly override the value of key '1' with the assignment of 'True' key... Try to: print(pairs) would output something like ( unordered dict ): {'orange': [2, 3, 4], 1:False, None: 'True'} However, you can define a '1' key as string instead of int, whithout overriding or be overrided by a True/1 key value: pairs = {'1': "apple", "orange": [2, 3, 4], True: False, None: "True", } print(pairs.get('1', "not in dictionary")) print(pairs.get("orange", "not in dictionary")) The output is what's expected, and: print(pairs) ...should output: {'1':'apple', 'orange': [2, 3, 4], True:False, None: 'True'}
31st Jan 2017, 9:41 PM
visph
visph - avatar