从字典中提取结果

时间:2016-10-10 03:20:57

标签: python python-2.7 dictionary

我有一本字典如下:

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

如何使用该字典制作以下结果。

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

我尝试如下:

for D.iteritems()中的x:     print x

无法弄清楚如何在此之后提取每个元素。 Alos想知道如何获得上述结果的好方法。

4 个答案:

答案 0 :(得分:1)

此版本应该更具可读性。但它们并不像其他版本那样具有普遍性。

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)

答案 1 :(得分:0)

这是一个几乎完全基于"recursive"-approach answer解决“扁平化词典”问题的解决方案:

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)

用法:

$ 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

这种方法的一大优势是它可以可扩展 - 它适用于字典D的不同深度。

答案 2 :(得分:0)

递归是你的朋友......

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,"")

打印::

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

注意有一个领先的空间,所以如果它寻找特定的输出,这个代码可能会失败测试,​​为了消除领先的空间,我们只需在else之后立即添加行s = s[1:] if len(s)>0 else s

答案 3 :(得分:0)

我建议使用递归解决方案来处理不同类型的数据:

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))

测试如下:

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

输出如下

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