PythonJSON 只能在第一级得到密钥

我有一个非常长和复杂的 json 对象,但我只想得到第一级的项目/键!

例如:

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

我想得到 一,三,八的结果!

我发现了这个代码:

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

但它打印所有键(也是 12岁和25岁)

331683 次浏览

Just do a simple .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
>>>

If you need a sorted list:

keylist = dct.keys() # this is of type `dict_key`, NOT a `list`
keylist.sort()

And if you want them as simple list, do this:

list(dct_instance.keys())
for key in data.keys():
print key

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

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


for key in dct.keys():
if isinstance(dct[key], dict)== False:
print(key, dct[key])
#shows:
# 1 a
# 3 b

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.