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):


  1. 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.

  1. 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.

  1. 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)


Receive my updates

Barış Özmen © 2025