Skip to main content
 首页 » 编程设计

python之嵌套字典python中的访问键

2024年10月01日12xiaohuochai

我有一个像下面这样的 JSON 对象。实际上是巨大的 JSON 文件,简化为问这个问题。

"header": { 
        "headerAttributes": { 
            "pageCount": 5, 
            "totalCount": 5 
        } 
    }, 
"payload": [ 
    { 
        "firstKey": [ 
                { 
                    "nestedKey_1": "1", 
                    "nestedKey_2": "2" 
                }, 
                { 
                    "nestedKey_3": "3", 
                    "nestedKey_4": "4" 
                } 
            ] 
    } 
] 

现在我在下面编写了 python 代码来访问 [] 中的值。

Total_Orders_Count = json_response ['header']['headerAttributes']['totalCount'] 
for i in range(0,Total_Orders_Count):  
            dict = json_response ['payload'][i] 
            inner_dict = dict ['firstKey'] [0] 
            print inner_dict ['nestedKey_1'] + '(' + inner_dict['nestedKey_2'] + ')' 

上面的代码工作正常。但是,dict ['firstKey'] [0] 的用法不适用于大于 1 的值。

两个问题。 1.有没有更好的方法来访问[]中的Key值。 2.我们可以找到[]中值的长度吗?对于此列表,“firstKey”下的值的长度为 2。

感谢任何帮助。

请您参考如下方法:

只需直接遍历列表。无需预先知道长度:

for d in json_response ['payload']: 
    for inner_dict in d['firstKey']: 
        print '{0[nestedKey_1]}({0]nestedKey_2})'.format(inner_dict) 

for <name> in <listobject>循环是一个 for each construct ;没有生成索引。相反,循环将列表中的每个元素分配给目标名称。

我改了名字dict至 d以避免掩盖内置类型。我也用过 string formatting将内部字典中的值放入字符串中。

请注意,我放弃了使用 totalCount关键完全。无需在此处查看该值。

至于查找列表的长度,只需使用 len() function .同样,此处无需使用该函数,直接在列表上迭代无需预先生成索引。