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>To answer your immediate question, you could just copy how dictionaries implement <code>dict.get</code> and <code>dict.__iter__</code>:</p>

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

    def __iter__(self):
        for attr in dir(self):
            if not attr.startswith('_') and attr != 'get':
                yield attr

    def get(self, key):
        return getattr(self, key)
</code></pre>

<p>It's not a very good approach, however. Looking at the attributes of your object at runtime isn't a good idea, because it will break when you subclass and it will add needless complexity. Instead, just use a dictionary internally:</p>

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

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

    def get(self, key):
        return self.container.get(key)
</code></pre>

python class for-loop