从字典中提取结果

2024-05-01 22:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下:

  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

我试了以下方法:

对于D.iteritems()中的x: 打印x

在那之后,我想不出如何提取每个元素。 想知道怎样才能得到上述结果。你知道吗


Tags: 方法park字典marketseattlekentamericaiteritems
3条回答

这个版本对你来说应该更具可读性。但它们不像其他版本那样具有普遍性。你知道吗

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)

递归是你的朋友。。。你知道吗

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。你知道吗

下面是一个几乎完全基于"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

这种方法的一个最大优点是它是可伸缩的,它适用于字典的不同深度。你知道吗

相关问题 更多 >