从python字典中获取所有子键的列表

从python字典中获取所有子键的列表,python,dictionary,recursion,nested,depth-first-search,Python,Dictionary,Recursion,Nested,Depth First Search,我有一些字典(json输出)。我想得到基本元素,它可以是字符串列表或字符串。目前我是这样做的:- folder="shared/" files=os.listdir('shared') for f in files: f=folder+f print(f) with open(f) as f: data = json.load(f) #data is a dict now with sub-keys for key,value in d

我有一些字典(json输出)。我想得到基本元素,它可以是字符串列表或字符串。目前我是这样做的:-

folder="shared/"
files=os.listdir('shared')


for f in files:
    f=folder+f
    print(f)
    with open(f) as f:
        data = json.load(f)
    #data is a dict now with sub-keys
    for key,value in data.items():
        if value.keys():
            print(value)
    break
这是python代码读取的输入字典:-

{
  "shortshirt": {
    "ralphlauren": {
      "classic": [
        "That Ralph Lauren classic fit is a timeless look!",
        "Nice choice. Can’t go wrong with Ralph Lauren"
      ]
    }
  },
  "socks": {
    "": {
      "": ["Have to find the right socks to keep your feet cozy"]
    }
  }
}
这是我得到的结果:-

{'ralphlauren': {'classic': ['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren']}}
{'': {'': ['Have to find the right socks to keep your feet cozy']}}
但这正是我想要的:-

keys=[["shortshirt","ralphlauren","classic"],["socks"]]

value=[['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren'], ['Have to find the right socks to keep your feet cozy']]

但我不知道是有2级还是3级嵌套循环。如果我有一个内部循环,并且实际上没有嵌套键,那么我会得到值错误。我想在一个单独的列表中获取所有嵌套键,以及另一个列表中最低级别的一个或多个基值,对此的任何帮助都将不胜感激。

生成器对解决此问题非常有用。战略——

  • 关键点:跟踪当前递归路径。一旦你碰到一片叶子,就产生当前路径

  • 价值观:只产树叶

代码:

输入:

{
  "shortshirt": {
    "ralphlauren": {
      "classic": [
        "That Ralph Lauren classic fit is a timeless look!",
        "Nice choice. Can't go wrong with Ralph Lauren"
      ]
    }
  },
  "socks": {
    "": {
      "": ["Have to find the right socks to keep your feet cozy"]
    }
  }
}
输出:

# keys
[['classic', 'ralphlauren', 'shortshirt'], ['socks']]

# values
[['That Ralph Lauren classic fit is a timeless look!', "Nice choice. Can't go wrong with Ralph Lauren"], ['Have to find the right socks to keep your feet cozy']]

你的描述不清楚。为您的示例数据提供相应的预期输出。我已编辑了问题。这是因为您没有深入字典,所以只获取顶级值(即DICT)。对于您想要的内容,您必须在字典中查找,直到值不是dict。您可以递归地执行此操作。钥匙也是一样,别忘了过滤空的。如果我往下走(添加一个循环),那么我怎么知道应该走多深?我的意思是,我要先写代码,如果我写3个循环,实际有5个子键,我将如何得到它们?递归,正如@JavierPazSedano提到的,那么不管有多少子键存在
# keys
[['classic', 'ralphlauren', 'shortshirt'], ['socks']]

# values
[['That Ralph Lauren classic fit is a timeless look!', "Nice choice. Can't go wrong with Ralph Lauren"], ['Have to find the right socks to keep your feet cozy']]