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>Here is a solution almost entirely based on the <a href="http://stackoverflow.com/a/6027615/771848">"recursive"-approach answer</a> for the "flattening the dictionary" problem:</p>

<pre><code>import collections


def flatten(d, parent_key='', sep=' '):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
</code></pre>

<p>Usage:</p>

<pre><code>$ ipython -i test.py
In [1]: D = {"America": {"Washington": {"Seattle": ('park', 'museum'), "Kent": ("market",)},
   ...:                  'Colorado': {"Boulder": ("hiking",)}}}

In [2]: for key, values in flatten(D, sep=" ").items():
   ...:     for value in values:
   ...:         print(key + " " + value)
   ...:         
America Washington Seattle park
America Washington Seattle museum
America Colorado Boulder hiking
America Washington Kent market
</code></pre>

<p>One of the biggest advantages of this approach is that it is <em>scalable</em> -  it would work for different depths of the dictionary <code>D</code>.</p>

python python-2.7 dictionary