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:
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']