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
• 5,910 points
179 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 9,380 points

Related Questions In Python

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
415 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
3,910 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
53 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by ariaholic
• 7,320 points
775 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
19 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
• 9,380 points
22 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
• 9,380 points
22 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.