Why Python Dictionary Keys Overwrite Each Other: Hashing, Equality & Identity
This article explores three Python quirks: how dictionary keys with equal numeric values overwrite each other due to hashing and equality rules, why a return statement inside a try block is superseded by a return in the finally clause, and how object identity and id values behave, including hash collisions and memory reuse.
First: Mysterious Dictionary Keys
some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"Output shows that the key 5.5 returns "Ruby", 5.0 returns "Python", and 5 returns "Python", because Python treats 5 and 5.0 as the same key (they are equal and have the same hash), so the later assignment overwrites the previous value.
Python dictionaries compare keys by equality and hash value.
Immutable objects with the same value have identical hash values.
Different objects can still share a hash (collision).
>> 5 == 5.0
True
>>> hash(5) == hash(5.0)
TrueThus assigning some_dict[5] = "Python" replaces the earlier "JavaScript" entry.
Second: Return in Exception Handling
def some_func():
try:
return 'from_try'
finally:
return 'from_finally'Calling some_func() returns 'from_finally' because the finally block always executes and its return overrides the one in try.
After a return, break, or continue in try, the finally clause still runs.
The function’s final return value is determined by the last executed return statement.
Third: Comparing Identical Objects
class WTF:
passExamples:
>> WTF() == WTF() # False
>>> WTF() is WTF() # False
>>> hash(WTF()) == hash(WTF()) # True (hash collision)
>>> id(WTF()) == id(WTF()) # True (ids can repeat after object destruction)Explanation: id() returns the memory address, which may be reused after an object is destroyed, so two separate objects can have the same id. The is operator checks identity, which remains False because the objects are distinct.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
