Explanation:
Step 1: Creating the Dictionary
d = {True: "A", 1: "B", 1.0: "C"}
Here, we are using three different-looking keys:
- True – Boolean value
- 1 – Integer value
- 1.0 – Float value
But Python has an interesting rule:
True == 1 == 1.0
Output:
True
All three values are equal, and they also have the same hash value.
hash(True) == hash(1) == hash(1.0)
Output:
True
Step 2: Understanding Dictionary Key Overwriting
Python dictionaries do not store duplicate keys when those keys are equal and have matching hash values.
Let's understand what happens internally:
Insertion Key Value Dictionary
1 True "A" {True: "A"}
2 1 "B" {True: "B"}
3 1.0 "C" {True: "C"}
Each new value replaces the previous value because the keys are considered equal.
Important: The original key object (True) remains in the dictionary, but its value gets updated to "C".
Step 3: Understanding len(d)
len(d)
- len() returns the number of key-value pairs.
- Since all three keys are treated as the same key, only one entry exists.
Output:
1
Step 4: Understanding d[True]
d[True]
- Python searches for the key True.
- The stored entry has the value "C".
- Therefore, it returns "C".
Step 5: Understanding the Complete Print Statement
print(len(d), d[True])
Execution:
1. len(d) returns 1.
2. d[True] returns "C".
3. print() displays both values separated by a space.
4. Final Output
1 C
.png)

0 Comments:
Post a Comment