Explanation:
Step 1: Understand the Dictionary
The code creates a dictionary with three key-value pairs:
{True: 1, 1: 2, 1.0: 3}
At first glance, it looks like the dictionary contains three different keys:
- True → 1
- 1 → 2
- 1.0 → 3
But there is a catch!
Step 2: Understand Python's Key Equality
In Python:
True == 1 # True1 == 1.0 # TrueTrue == 1.0 # True
These values are different types, but they compare equal.
Python also gives them the same hash value, so they refer to the same dictionary key.
Step 3: Understand Dictionary Overwriting
When Python encounters these entries:
{True: 1, 1: 2, 1.0: 3}
It processes them from left to right.
1. True: 1 — inserts the first entry.
2. 1: 2 — updates the value for the existing key.
3. 1.0: 3 — updates that same key again.
The resulting dictionary has just one entry, with the value 3.
{True: 3}
The original key object (True) is retained, while its value is updated.
Step 4: Access the Dictionary Using [1]
{True: 3}[1]
Because 1 is equal to True and has the same hash, Python finds the existing key and returns its value:
3
Step 5: Final Output
3
.png)
