97

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

Example:

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

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

I found this code:

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

But it prints all keys (also 12 and 25)

karthikr
  • 92,866
  • 25
  • 190
  • 186
TeNNoX
  • 1,645
  • 2
  • 15
  • 26
  • 6
    No, it doesn't. It prints the keys, and the values which themselves include the sub-dictionaries. If you just want to print the keys, don't print the value. – Daniel Roseman Apr 03 '13 at 13:46
  • possible duplicate of [Python: how to print a dictionary's key?](http://stackoverflow.com/questions/5904969/python-how-to-print-a-dictionarys-key) – Joe Frambach Apr 03 '13 at 13:51
  • 1
    But i don't want subdictionary keys... I know i could ommit the ",value" this was just for debugging purpose – TeNNoX Apr 03 '13 at 14:03

4 Answers4

158

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()
karthikr
  • 92,866
  • 25
  • 190
  • 186
  • @karthikr how to get the output as 1, 3, 8.12, 8.25. Basically I want the output to have parent and child keys separated by some delimiter – JKC Jul 30 '19 at 04:00
22
for key in data.keys():
    print key
Joe Frambach
  • 26,300
  • 10
  • 69
  • 98
5

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.

Praveen Manupati
  • 354
  • 1
  • 6
  • 11
3

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
Hafizur Rahman
  • 2,104
  • 19
  • 29