+ 3

Why can't I use the integers 0 or 1 as a key in a dictionary with the function get(), when I use a boolean as another key?

When I use a boolean True or False as a key, I get as an output the value of this key when I put the integers 0 or 1 into the function get, even if I have one key named as the intenger 1 or 0. 0(integer) is regard to False(Boolean) and 1(integer) is regard to True (Boolean) as keys in a dictionary. In the example bellow, when I remove the pair with the boolean key (True:False), I can take the value "apple" of the key 1. So I can't access the keys 0/1 when I have a correspondent boolean as a key. Example: pairs = {1: "apple", "orange": [2, 3, 4], True: False, 12: "True", } print(pairs.get("orange")) #output >>> [2,3,4] print(pairs.get(7, 42)) #output >>> 42 print(pairs.get(12345, "not found")) #output >>> not found print(pairs.get(1)) #output >>> False

20th Apr 2021, 4:10 PM
Camila Pires
Camila Pires - avatar
9 Antworten
+ 7
You said the reason yourself "0(integer) is regard to False(Boolean) and 1(integer) is regard to True (Boolean) as keys in a dictionary" In the same way, True is also regarded as 1. So when you use True as key, it overwrites the 1. To help you understand better, in a dictionary, each key irrespective of the type (even strings and tuples) is converted to an integer using certain algorithms. This integer value is the 'hashed' value of that key. It can be accessed using the hash() function. For strings and other objects, this value may be different each time the program is run. But for constants like integers, it is the same hash(2) # always returns 2 hash(10) # always returns 10 Now what do you think might be the integer value for True? 1 of course! So True can overwrite 1 in a dictiinary
20th Apr 2021, 4:30 PM
XXX
XXX - avatar
+ 2
I suppose 1:"apple" gets right away overwritten by True:False because 1 == int(True). So we cannot have True and 1 at the same as different key values -- they are the same
20th Apr 2021, 4:25 PM
Lisa
Lisa - avatar
+ 2
Camila Pires correct. But actually, Python considered True as the integer 1, and not the opposite,
20th Apr 2021, 4:33 PM
XXX
XXX - avatar
+ 1
When I ran the code to understand get(), I got very confused, because when I used 1 and some value, I got always False as an output. So after many tryings, I got it, Python considered the intenger 1 as True. :-/ hahahaha
20th Apr 2021, 4:31 PM
Camila Pires
Camila Pires - avatar
0
Dude😳 Thats different datatypes wdym😳 You can only convert the bools to 0 and 1 but not at this case. Here you use them as keys so they're immutable
20th Apr 2021, 4:22 PM
Nazeekk
Nazeekk - avatar
0
0 and 1 is also one type of boolean. 0 = false and 1 = true. You already declare boolean as key thats why you cant assign as same key another time.
22nd Apr 2021, 1:28 PM
MinhAj RahmAn
MinhAj RahmAn - avatar
- 1
I am too beginner so far 🤦‍♂️! Need to learn a lot more 😔
22nd Apr 2021, 11:59 AM
Javed Ullah
Javed Ullah - avatar