为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

撒科打诨 2021-12-09 16:36:36
我有一些字典(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 级嵌套循环。如果我有一个内部循环并且实际上没有嵌套键,那么我会得到值错误。我想在一个单独的列表中获取所有嵌套的键和一个或多个基本值,例如另一个列表中最低级别的值,对此的任何帮助将不胜感激。
查看完整描述

1 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

生成器对这个问题很有用。策略——


Keys:跟踪当前的递归路径。一旦你碰到一片叶子,就让出当前的路径。


值:只产生叶子。


代码:


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']]



查看完整回答
反对 回复 2021-12-09
  • 1 回答
  • 0 关注
  • 280 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号