python JSON only get keys in first level
Solution 1:
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()
Solution 2:
for key in data.keys():
print key
Solution 3:
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.