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

问题描述 投票:3回答:1

我有一些词典(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级嵌套循环。如果我有一个内循环,实际上没有嵌套键,那么我得到值错误。我希望将所有嵌套键放在一个单独的列表中,并将基本值或值放在另一个列表中的最低级别,任何有关此问题的帮助都将受到高度赞赏。

python dictionary recursion nested depth-first-search
1个回答
1
投票

生成器对此问题很有用。策略 -

  • 键:跟踪当前的递归路径。一击到叶子就产生当前路径。
  • 价值观:只产生叶子。

码:

def getitems(obj):

  def getkeys(obj, stack):
    for k, v in obj.items():
      k2 = ([k] if k else []) + stack # don't return empty keys
      if v and isinstance(v, dict):
        for c in getkeys(v, k2):
          yield c
      else: # leaf
        yield k2

  def getvalues(obj):
    for v in obj.values():
      if not v: continue
      if isinstance(v, dict):
        for c in getvalues(v):
          yield c
      else: # leaf
        yield v if isinstance(v, list) else [v]

  return list(getkeys(obj,[])), list(getvalues(obj))

输入:

{
  "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']]
© www.soinside.com 2019 - 2024. All rights reserved.