Mohamed Amine
Mohamed Amine

Reputation: 582

dictionary showing false results python

I tried to define this dictionary but when I print it I get different results:

pairs = {1: "apple", "orange": [2, 3, 4],  True: False, None: "True"}

output = {1: False, None: 'True', 'orange': [2, 3, 4]}

Upvotes: 1

Views: 236

Answers (2)

Ibrahim Noor
Ibrahim Noor

Reputation: 259

the main discrepancy that you are facing is 1: False instead of {1: "apple", True: False}.

The reason it is happening is because in python and most programming languages, True is interpreted as 1. If you type print True==1, it will print True, showing that python treats them as equal. So your dictionary:

pairs = {1: "apple", "orange": [2, 3, 4], True: False, None: "True"}

is interpreted as:

pairs = {1: "apple", "orange": [2, 3, 4], 1: False, None: "True"}

Now in python dictionaries, you can not have duplicate keys. If you try to add two same keys, the value of the second one will overwrite the value of the first one. In your case, since 1:False comes after 1:"apple", False will overwrite "apple" as the value 1. I hope that clears up everything.

Upvotes: 3

SpaceBurger
SpaceBurger

Reputation: 549

The statement pairs[True] = False is interpreted as pairs[1] = False. That way, we have :

>>> pairs = {1: "apple", "orange": [2, 3, 4], None: "True"}
>>> pairs
{1: 'apple', 'orange': [2, 3, 4], None: 'True'}
>>> pairs[True] = False
>>> pairs
{1: False, 'orange': [2, 3, 4], None: 'True'}
>>>

Upvotes: 4

Related Questions