Python dictionary keys() return a dict_keys object, instead of list, causing awkward behavior
2025-03-02 python pythonquirk til
Example
d = {"a": 1, "b": 2}
keys_view = d.keys()
print(keys_view) # dict_keys(['a', 'b'])
d["c"] = 3 # Modify the dictionary
print(keys_view) # dict_keys(['a', 'b', 'c']) -> Updates automatically!
Key reasons for this design choice (per chatgpt):
- Efficient Memory Usage: A view object does not create a separate list of keys. Instead, it dynamically reflects the dictionary's keys without extra memory overhead. This is important for large dictionaries, where copying all keys into a list would be expensive.
- Dynamic Updates (Live View): A dictionary view object updates automatically when the dictionary changes. If keys are added or removed, the view reflects these changes without needing to regenerate the list.
- Set-Like Behavior: dict_keys behaves like a set, meaning it supports fast membership testing (in operation). This allows efficient operations like set intersections with other collections.
Also see Python Design and History FAQ
Couldn't find anything in Neopythonic - Guido Van Rossum's blog about this
Incoming Internal References (0)
Outgoing Internal References (0)
Outgoing Web References (3)
-
chatgpt.com/share/67c49cce-b0f8-8010-9929-9487d743a648
- chatgpt
-
docs.python.org/3/faq/design.html#why-am-i-getting-strange-results-with-simple-arithmetic-operations
- Python Design and History FAQ
-
neopythonic.blogspot.com
- Neopythonic - Guido Van Rossum's blog