+ 2

How does 'get' in 'dictionaries' work?

Suppose this code: p = { 1: 2, 2: 4, 4: 8, 8: 16, True:False } print(p.get(1)) p2 = { 1: 2, 2: 4, 4: 8, 8: 16, } print(p2.get(1)) #------------------------------------ why the 1st output is False and the second one is 2 ?? based on previous learning, both of them must be the same. please elaborate more on that.

12th Jul 2017, 11:20 AM
۱۶ۧ ŰŽÙÙ‚ÛŒ
۱۶ۧ ŰŽÙÙ‚ÛŒ - avatar
3 Answers
+ 1
on the other hand, in the 1st code, 'p.get(1)' must refer to '2' and must explain why it refer to 'False'?
12th Jul 2017, 11:14 AM
۱۶ۧ ŰŽÙÙ‚ÛŒ
۱۶ۧ ŰŽÙÙ‚ÛŒ - avatar
+ 1
Python dictionaries don't support duplicate keys. so as True also corresponds to 1, the value for key 1 is overwritten and it becomes False. There are ways you need to support duplicate keys in python e.g defaultdict:
13th Jul 2017, 5:28 AM
J Prak
J Prak - avatar
0
it is because the default value of True is 1 , since it is a keyword . use 'true' instead of 'True'
11th Jul 2017, 1:57 PM
Kedar Kale
Kedar Kale - avatar