What happens when I loop a dict in python
<p>I know <code>Python</code> will simply return the key list when I put a <code>dict</code> in <code>for...in...</code> syntax.</p>

<p>But what what happens to the dict?</p>

<p>When we use <code>help(dict)</code>, we can not see <code>__next()__</code> method in the method list. So if I want to make a derived class based on <code>dict</code>:</p>

<pre><code>class MyDict(dict)
    def __init__(self, *args, **kwargs):
        super(MyDict, self).__init__(*args, **kwargs)
</code></pre>

<p>and <strong>return the value list with <code>for...in...</code></strong></p>

<pre><code>d = Mydict({'a': 1, 'b': 2})
for value in d:
</code></pre>

<p>what should I do?</p>

<p>Naively, if all you want is for iteration over an instance of <code>MyClass</code> to yield the values instead of the keys, then in <code>MyClass</code> define:</p>

<pre><code>def __iter__(self):
    return self.itervalues()
</code></pre>

<p>In Python 3:</p>

<pre><code>def __iter__(self):
    return iter(self.values())
</code></pre>

<p>But beware! By doing this your class no longer implements the contract of <code>collections.MutableMapping</code>, even though <code>issubclass(MyClass, collections.MutableMapping)</code> is True. You might be better off <em>not</em> subclassing <code>dict</code>, if this is the behaviour you want, but instead have an attribute of type <code>dict</code> to hold the data, and implement only the functions and operators you need.</p>

python dictionary