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>I would suggest recursive solution  to work with your different kind of data:</p>

<pre><code>def printX(data, prefix=''):
    if isinstance(data, dict):
        for itemKey, itemValue in data.iteritems():
            newPrefix = '{} {}'.format(prefix, itemKey)
            printX(itemValue, newPrefix)
    elif isinstance(data, tuple):
        for itemValue in data:
            printX(itemValue, prefix)
    else:
        print('{} {}'.format(prefix, data))
</code></pre>

<p>Did a test as below:</p>

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

<p>Output is as below</p>

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

python python-2.7 dictionary