dragon dragon - 1 year ago 102
Python Question

Extract results from a dictionary

I have a dictionary as follows:

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

how can I make the following results using that dictionary.

America Wahington Seattle park
America Wahington Seattle museum
America Wahington Kent market
America Colorado Boulder hiking

I tried as follows:

for x in D.iteritems():
print x

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.

Answer Source

This versions should be more readable for you. But they are not so universal like other versions.

for country in D:
    for state in D[country]:
        for city in D[country][state]:
            for place in D[country][state][city]:
                print(country, state, city, place)

for country, A in D.items():
    for state, B in A.items():
        for city, C in B.items():
            for place in C:
                print(country, state, city, place)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download