Python - changing values of a dictionary when using itervalues()

dictionary, iterator, python

Solution

If you mean constructs like:

d = {1: [1]}
for v in d.itervalues():
    v[0] += 1

then yes, this is completely safe. The `dict` just stores a reference to the object in question and does not touch it in any way other than storage and retrieval. This is not explicitly documented, but it is implicit in the definition of mapping (of which `dict` is a subtype):

A mapping object maps hashable values to arbitrary objects.

"Arbitrary" means the object may be mutable.

Problem

I'm wondering if it is OK to modify the values of a Python dictionary when it doesn't depend on the keys: ``` # d is some dictionary containing classes I wrote for v in d.itervalues(): # modify v, and v's type may or may not change ``` I'm not sure what the Python standard says about this, could somebody please provide some information? Thanks!

Original source