python JSON only get keys in first level

python JSON only get keys in first level

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()
keylist.sort()
for key in data.keys():
    print key

python JSON only get keys in first level

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.

Leave a Reply

Your email address will not be published. Required fields are marked *