Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would you access sub-dictionaries in a nested json response dictionary when the primary (first level) dictionary key varies?

I have a json response like this:

{'3830': {'success': True, 'data': {'categories': [{'id': 2, 'description': 'Single-player'}, {etc...

I would like to access the sub-dictionary categories, however the primary dictionary key, 3830 in the above example, varies. The json response is the result of requests.get iterating through a list, thus the primary dictionary key changes with each response. I can’t figure out how to set a variable within the function that contains the contents of categories.

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data = await response.json()
mp_data = data['3830']['data']['categories']

which of course worked for the first iteration as the 3830 matched, but failed with KeyError on following iterations. Also tried using a variable for first level like ['*'] and [*] but this didn’t work either.

Any ideas on the best way to do this? Is it possible?

>Solution :

If it is always the first key that you want to access, use

first_key = list(data.keys())[0]

Or

first_key = next(data.keys())

To get the first key and then use this to access the lower level data

mp_data = data[first_key]['data']['categories']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading