簡體   English   中英

將嵌套字典展平為列表列表

[英]Flatten nested dictionary into a list of lists

我有一個代碼,因此得到一個像這樣的嵌套字典:

{'weather': {'cloudy': 'yes',
         'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}},
         'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}

現在我需要將它“展平”到這樣的列表列表中:

[[weather, cloudy, yes], [weather, rainy, wind, strong, no], [weather, rainy, wind, weak, yes], ...]

我已經嘗試了許多不同的方法來解決這個問題,但就是無法做到正確,有沒有人遇到過類似的問題?

編輯:有人要求看我的一些試驗,我試過把它變成一個列表來做這樣的事情:

def change(self, tree):
    l = []
    for key, value in tree.items():
        l.append(key)
        if type(value) is dict:
            l.extend(change(value))
        else:
            l.append(value)

    return l

這返回:

['weather', 'cloudy', 'yes', 'rainy', 'wind', 'strong', 'no', 'weak', 'yes', 'sunny', 'humidity', 'high', 'no', 'normal', 'yes']

這不是我需要的,但我不知道如何解決它。

您可以使用遞歸生成器 function:

d = {'weather': {'cloudy': 'yes', 'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}}, 'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}
def flatten(d, c = []):
   for a, b in d.items():
      yield from ([c+[a, b]] if not isinstance(b, dict) else flatten(b, c+[a]))

print(list(flatten(d)))

Output:

[['weather', 'cloudy', 'yes'], ['weather', 'rainy', 'wind', 'strong', 'no'], ['weather', 'rainy', 'wind', 'weak', 'yes'], ['weather', 'sunny', 'humidity', 'high', 'no'], ['weather', 'sunny', 'humidity', 'normal', 'yes']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM