python JSON只获取第一级的键

python JSON only get keys in first level(python JSON只获取第一级的键)
本文介绍了python JSON只获取第一级的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个很长很复杂的 json 对象,但我只想获取第一级的项目/键!

I have a very long and complicated json object but I only want to get the items/keys in the first level!

例子:

{
    "1": "a", 
    "3": "b", 
    "8": {
        "12": "c", 
        "25": "d"
    }
}

我想得到 1,3,8 作为结果!

I want to get 1,3,8 as result!

我找到了这段代码:

for key, value in data.iteritems():
    print key, value

但它会打印所有键(还有 12 和 25)

But it prints all keys (also 12 and 25)

推荐答案

只要做一个简单的.keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

如果您需要排序列表:

keylist = dct.keys()
keylist.sort()

这篇关于python JSON只获取第一级的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

python: iterating through a dictionary with list values(python:遍历具有列表值的字典)
What is the difference between chain and chain.from_iterable in itertools?(itertools中chain和chain.from_iterable有什么区别?)
Iterate over n successive elements of list (with overlapping)(迭代列表的 n 个连续元素(重叠))
Loop problem while iterating through a list and removing recurring elements(遍历列表并删除重复元素时出现循环问题)
Elegant way to skip elements in an iterable(跳过可迭代元素的优雅方式)
#39;numpy.float64#39; object is not iterable(numpy.float64 对象不可迭代)