Second level looping over dictionaries
<p>In building a class with an out line like below I would like the behaviour of  the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the second loop.  The problem I can't figure out is how to set up this under <strong>iter</strong>.     </p>

<pre><code>class MyClass():
    def __init__(self):
        self.cont1 = [1,2,3,4]
        self.cont2 = ('a','b','c')

def __iter__(self):
    pass # ???????
</code></pre>

<p>Something like this:</p>

<pre><code>dct = dict(container1=[5,6,7,8], container2=('a','b','c')

if one loop is used:

   for ea in dct:
        print(ea)
print("Howdy")

'containter1'
'containter2'
Howdy
</code></pre>

<p>If a nest loop is used:</p>

<pre><code>for ea in dct:
    print(ea)
    for i in dct.get(ea):
        print(i)

'container1'
5
6
...
'container2'
a
b
c
</code></pre>

<p>How would you feel about this:</p>

<pre><code>class MyClass():
    def __init__(self):
        self.cont1 = [1,2,3,4]
        self.cont2 = ('a','b','c')
        self.conts = {'container1':self.cont1, 'container2':self.cont2}

    def __iter__(self):
        return self.conts.iteritems()

dct = MyClass()
print('One loop')
for mi in dct:
    print(mi)
print('='*40)
print('Nested loops')
for name, values in dct:
    print(name)
    for i in values:
        print(i)
</code></pre>

<p>Which outputs:</p>

<pre><code>One loop
container1
container2
========================================
Nested loops
container1
1
2
3
4
container2
a
b
c
</code></pre>

<h2>Update</h2>

<hr>

<p>I don't know that I would really recommend this, but this seems to more closely fit what the OP wants:</p>

<pre><code>class MyIterator(object):
    def __init__(self, name, values):
        self.vals = iter(values)
        self.name = name

    def __iter__(self):
        return self.vals

    def __str__(self):
        return self.name


class MyClass():
    def __init__(self):
        self.cont1 = [1,2,3,4]
        self.cont2 = ('a','b','c')
        self.conts = [MyIterator('container1', self.cont1),
                      MyIterator('container2', self.cont2)]

    def __iter__(self):
        return iter(self.conts)

dct = MyClass()
for mi in dct:
    print(mi)
    for i in mi:
        print(i)
</code></pre>

<p>This is the only way I can think of to be able to print the name and then iterate over it as the values list. This works by overriding the <code>__str__</code>  method to change how the object gets "stringified". But as I said earlier, I think you would be better served with the first part of the answer.</p>

<p>Sorry, just realized <a href="http://stackoverflow.com/a/39754576/3901060">nauer's answer</a> already showed something like this.</p>

python class for-loop