从多嵌套字典捕获python值

2024-05-15 22:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图用以下代码片段获取CategoryParentID

print dicstr['CategoryParentID']

我的字典是这样的:

{
    "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'

Tags: 代码inpytrueget字典linefile
3条回答

当您要求Python给您dicstr['CategoryParentID']时,您要做的是给您与dicstr中的键'CategoryParentID'关联的值

看看你的字典是怎么定义的。dictstr的键将是正好在dictstr下一级的所有键。这些是Python在指定dictstr['CategoryParentID']时试图查找CategoryParentID的关键。这些键是:

"CategoryCount"

"UpdateTime"

"Version"

"Ack"

"Timestamp"

"CategoryArray"

注意你要找的钥匙不在那里。这是因为它嵌套在dictstr的更深层次。在找到CategoryParentID键之前,您需要一直“跳跃”这些键。尝试:

dictstr['CategoryArray']['Category'][0]['CategoryParentID']

注意这里的[0]。与'Category'键关联的值是一个列表。该列表包含一个元素,即字典。为了访问字典(它包含您实际需要的键),您必须在保存字典的索引处索引到列表中。因为只有一个元素,所以使用[0]直接索引到该元素以获取字典,然后继续“跳跃”键

你得先浏览一下字典CategoryParentID在一个列表中(因此[0]),它的值是Category,它的值是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'

你得把它弄得像-

x['CategoryArray']['Category'][0]['CategoryParentID']

如果我们简化你发布的内容,我们会得到-

d = {'CategoryArray': {'Category': [{'CategoryParentID': '20081'}]}}
# "CategoryArray" 
# "Category" child of CategoryArray 
#  Key "Category" contains a list [{'CategoryName': 'Antiques', 'CategoryParentID': '20081'...}]
#  Get 0th element of key "Category" and get value of key ["CategoryParentID"]

我希望这有道理

相关问题 更多 >