Extract results from a dictionary
<p>I have a dictionary as follows:</p>

<pre><code>  D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } }
</code></pre>

<p>how can I make the following results using that dictionary.</p>

<pre><code>America Wahington Seattle park
America Wahington Seattle museum
America Wahington Kent market
America Colorado Boulder hiking
</code></pre>

<p>I tried as follows:</p>

<p>for x in D.iteritems():
    print x</p>

<p>Could not figure out how to extract each elements after that.
Alos wan to to how is the good way of getting the above result.</p>

<p>Recursion is your friend...</p>

<pre><code>D = { "America": { "Washington": { "Seattle": ('park', 'museum'), "Kent": ("market",) }, 'Colorado': { "Boulder": ("hiking",) } } }

def printOut(d,s):
    if(type(d)==dict):
        for k in d.keys():
            printOut(d[k],s+" "+str(k)) # add the key to a string and pass the contained dictionary and the new string to the same function. (this is the recursive part...)
    else:
        try:                      # this try catch allows the method to handle iterable and non-iterable leaf nodes in your dictionary.
            for k in d:
                print s+" "+str(k)
        except TypeError:
                print s+" "+str(d)

printOut(D,"")
</code></pre>

<p>prints::</p>

<pre><code> America Washington Seattle park
 America Washington Seattle museum
 America Washington Kent market
 America Colorado Boulder hiking
</code></pre>

<p>notice that there is a leading space so this code might fail a test if it looking for a specific output, to eliminate the leading space we would simply add the line <code>s = s[1:] if len(s)&gt;0 else s</code> immediately after the else.</p>

python python-2.7 dictionary