python JSON only get keys in first level

0 votes
Here is a very long and complicated json object but what should I do if 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)
Jan 22 in Python by ana1504.k
• 7,470 points
565 views

1 answer to this question.

0 votes
You just need 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()
answered Jan 22 by SDeb
• 12,360 points

Related Questions In Python

0 votes
0 answers

How can i get the content in the JSON format while making the GET requests in python?

While making POST requests how can we ...READ MORE

Jun 6 in Python by Waseem
• 3,480 points
11 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
550 views
0 votes
2 answers

Extracting data from a JSON file in Python

Here is what i found and was ...READ MORE

answered Nov 27, 2018 in Python by Rupali
5,727 views
0 votes
1 answer

Parse JSON in Python

import json data=json.loads(employee_data) print(data) READ MORE

answered Apr 26, 2018 in Python by aayushi
• 750 points
62 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 128 views
0 votes
1 answer

Get the Current time in Python

To get the current date and time ...READ MORE

answered Oct 3, 2018 in Python by SDeb
• 12,360 points
42 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 12,360 points
44 views