从多嵌套字典中捕获python值 [英] Capture python value from multi-nested dictionary

查看:73
本文介绍了从多嵌套字典中捕获python值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从多嵌套词典获取变量时遇到一些问题.

I'm having some problems obtaining a variable from a multi-nested dictionary.

我正在尝试使用以下代码段抓取 CategoryParentID :

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"
            },
.
.
.
}

但是,我遇到此错误:

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'

推荐答案

您需要先遍历字典. CategoryParentID 在列表中(因此为 [0] ),该列表为 Category 的值,而 CategoryArray 的值为>

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'

这篇关于从多嵌套字典中捕获python值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆