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, 2019 in Python by ana1504.k
• 7,910 points
22,198 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()

Hope it helps!!

If you need to know more about Python, It's recommended to join Python course today.

Thanks!

answered Jan 22, 2019 by SDeb
• 13,300 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, 2019 in Python by Waseem
• 4,540 points
433 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
3,226 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
29,281 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
992 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
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
• 13,300 points
480 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
• 13,300 points
692 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP