After reading What are Python dictionary view objects? and … what are the performance tradeoffs …? and the official documentation about views on Python dictionaries, I still lack a decent usecase which makes me understand why they are there.
The idea is to have a view on the dictionary which has two major differences to creating a list of the keys/values/items: ① It's faster created (in constant time) and with constant amount of memory footprint and ② it reflects changes in the dictionary also after its creation.
This is fine and understood but I lack an idea when it would be useful to have this. After all wherever I pass such a view, I could pass the dictionary itself instead. It will also be passed in constant time without additional memory footprint and it will also reflect changes on itself (of course). Whatever I would want to do with the view I could also do with the passed dictionary itself. Or am I missing something?
Someone mentioned that using iteritems()
(iter()
in Python3) on a dictionary while it was changing would invalidate the iterator. This is true. Unfortunately this is likewise true for any iterator created to iterate over a view. So again there is no difference.
So what's the benefit of using a view? Is there any practical usecase which goes beyond what can be found in the older questions linked above?