I’m having some problems obtaining a variable from a multi-nested dictionary.
I’m trying to grab CategoryParentID
with the following snippet:
print dicstr['CategoryParentID']
while my dictionary looks like this:
{
"CategoryCount": "12842",
"UpdateTime": "2018-04-10T02:31:49.000Z",
"Version": "1057",
"Ack": "Success",
"Timestamp": "2018-07-17T18:33:40.893Z",
"CategoryArray": {
"Category": [
{
"CategoryName": "Antiques",
"CategoryLevel": "1",
"AutoPayEnabled": "true",
"BestOfferEnabled": "true",
"CategoryParentID": "20081",
"CategoryID": "20081"
},
.
.
.
}
I’m getting this error, however:
Traceback (most recent call last):
File "get_categories.py", line 25, in <module>
getUser()
File "get_categories.py", line 18, in getUser
print dictstr['CategoryParentID']
KeyError: 'CategoryParentID'
3
Answers
You need to first traverse the dictionary.
CategoryParentID
is in a list (hence[0]
) which is a value ofCategory
which is a value ofCategoryArray
You’ll have to get it like –
If we simplify the dict you posted, we get –
I hope it makes sense
When you ask Python to give you
dicstr['CategoryParentID']
, what you’re asking it to do is to give you the value that’s associated with the key'CategoryParentID'
indicstr
.Look at the way your dictionary is defined. The keys of
dictstr
are going to be all the keys that are exactly one level underdictstr
. These are the keys Python is looking at to try to findCategoryParentID
when you specifydictstr['CategoryParentID']
. These keys are:"CategoryCount"
"UpdateTime"
"Version"
"Ack"
"Timestamp"
"CategoryArray"
Notice that the key you’re looking for isn’t there. That’s because it’s nested several levels deeper in
dictstr
. You need to keep “hopping along” these keys until you get to theCategoryParentID
key. Try:dictstr['CategoryArray']['Category'][0]['CategoryParentID']
Note the
[0]
in there. The value that’s associated with the'Category'
key is a list. That list contains one element, which is a dictionary. In order to get to the dictionary, which holds the key you actually want, you have to index into the list at the index that holds the dictionary. Since there’s only one element, index directly into it using[0]
to get the dictionary, and then continue to “hop along” the keys.