Python 3 dictview ... dict().keys, .values(), .items() are dynamic

Posted by: Rod Morison 7 years, 5 months ago

(0 comments)

Simply stated,

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']

However, this construct no longer works,

>>> dishes.items()[1]
>>> # e.g., instead:
>>> list(dishes.items())[1]

from Dictionary view objects

Comments

  • There are currently no comments

New Comment

required
required (not published)
optional