【问题标题】:Python, get dictionary, nested dictionary, nested list keysPython,获取字典,嵌套字典,嵌套列表键
【发布时间】:2021-05-10 17:06:20
【问题描述】:

我正在尝试从 Python 中的 json 文件中获取所有密钥。 如何获得嵌套的第二级(x,y)和第三级键(a,b)。 例如,Keys: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))

json:

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

输出:

Keys : results

【问题讨论】:

    标签: python json key


    【解决方案1】:

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

    因此,您需要遍历 my_dict 的值而不是键。

    【讨论】:

    • 有值我得到了一切 输出:(results[{'x': 5}, {'x': 5, 'y': [1, 2, 3]}, {'x' : 5, 'y': {'a': 2, 'b': 67}}])
    【解决方案2】:

    使用递归函数返回所有嵌套键。这是参考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))
    

    【讨论】:

    • 我仍然只得到“结果”键
    • 我明白了,因为你的字典中'results'键的值是list,所以上面的代码不能正常工作。 @NoemonGR 编辑了答案,立即查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多