Search code examples
pythonsdkebay-api

Capture python value from multi-nested dictionary


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'

Solution

  • You need to first traverse the dictionary. CategoryParentID is in a list (hence [0]) which is a value of Category which is a value of CategoryArray

    dicstr = {'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'}]
          }
      }
    
    dicstr['CategoryArray']['Category'][0]['CategoryParentID']
    '20081'