Python,获取字典,嵌套字典,嵌套列表键

时间:2021-02-06 15:54:37

标签: python json key

我正在尝试从 Python 中的 json 文件中获取所有密钥。 如何获得嵌套的二级(x,y) 和三级键(a,b)。 例如,键:results,x,y,a,b

代码:

#open data
import json

with open('list.json') as f:
    my_dict = json.load(f)

#1
    #find keys
    for key in my_dict.keys():
         print("Keys : {}".format(key))

杰森:

{
   "results":[
      {
         "x":5
      },
      {
         "x":5,
         "y":[
            1,
            2,
            3
         ]
      },
      {
         "x":5,
         "y":{
            "a":2,
            "b":67
         }
      }
   ]
}

输出:

Keys : results

2 个答案:

答案 0 :(得分:0)

使用递归函数返回所有嵌套的键。这是参考 stackoverflow 页面。

import json

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is list:
            for i in value:
                if type(i) is dict:
                    yield from recursive_items(i)
        else:
            yield key

with open('list.json') as f:
    my_dict = json.load(f)

    #find keys
    for key in recursive_items(my_dict):
         print("Keys : {}".format(key))

答案 1 :(得分:0)

您需要获取作为 JSON 值一部分的键。

因此您需要迭代 my_dict 的值而不是键。