【问题标题】:Navigating nested dictionary导航嵌套字典
【发布时间】:2020-10-09 19:48:22
【问题描述】:

我正在努力思考如何导航嵌套在列表中的一系列字典。

例如:mydict = {'first':[{'second':2, 'third':3}, {'fourth':4}]}

当我输入mydict.get('first') 时,我会得到整个列表。

我不能使用索引来获取列表中的每个单独的字典(即mydict.get(['first'][0] 返回整个列表,mydict.get(['first'][1]) 返回一个 IndexError)。

mydict.get(['first'][0]['second'])mydict.get(['first']['second']) 返回类型错误。

那么,如果我想调用 'second' 或 'fourth' 或将它们的值分配给变量,我该怎么做呢?

【问题讨论】:

    标签: python dictionary nested


    【解决方案1】:

    第二个: mydict['first'][0]['second]

    ['first'] 返回数组
    [0] 返回数组的第一个对象
    ['second'] 获取“第二个”对象

    也许尝试将您的数据重塑为更方便的方式?

    【讨论】:

      【解决方案2】:

      在您的示例中,mydict 不是嵌套在列表中的一系列字典。它是一个包含列表的字典,而列表又包含字典。

      因此,假设您不知道哪个内部字典将包含您要查找的键,则必须遍历父字典中的所有条目才能找到它。比如:

      desiredKey = 'second'
      for listOfDict in mydict.values():
        for childDict in listOfDict:
          if desiredKey in childDict:
            print(childDict[desiredKey])
      

      仅当您要查找的键始终在最里面的字典中时,这才有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-29
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        • 2018-04-15
        • 2021-12-20
        • 2012-01-29
        相关资源
        最近更新 更多