从多嵌套字典中获取变量时遇到一些问题
我试图用以下代码片段获取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'
当您要求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
你得把它弄得像-
如果我们简化你发布的内容,我们会得到-
我希望这有道理
相关问题 更多 >
编程相关推荐