TypeError:尝试从字典中访问值时,字符串索引必须为整数

时间:2019-04-16 20:34:03

标签: python

我有这样的字典:

data = {
   "4.3.0 Test Plan":{
      "Engine":{
         "passed_count":0,
         "blocked_count":0,
         "untested_count":4088,
         "failed_count":0,
         "reviewed_count":0,
         "test_harness_issue_count":0,
         "bug_failure_count":0,
         "defect_list":[

         ]
      },
      "Management Web Console":{
         "passed_count":0,
         "blocked_count":0,
         "untested_count":12067,
         "failed_count":0,
         "reviewed_count":0,
         "test_harness_issue_count":0,
         "bug_failure_count":0,
         "defect_list":[

         ]
      }
   }
}

我正在尝试通过以下方式访问两个类别的untested_count值:

for value in data["4.3.0 Test Plan"]:
    print(value)
    print(value['untested_count'])

但是我在此行TypeError: string indices must be integers上收到此错误print(value['untested_count'])

并且还在同一行上从我的python IDE Expected type 'Union[int, slice]', got 'str' instead接收到此错误

对于为什么会这样,我感到很困惑,对此示例中有关此错误的任何帮助和解释将不胜感激

注意:上面的for循环中的print(value)会返回:

Engine
Management Web Console

预期结果:

Engine
4088
Management Web Console
12067

1 个答案:

答案 0 :(得分:3)

您要遍历字典的keys,而可以使用keys遍历valuesitems()

for key, value in data["4.3.0 Test Plan"].items():
   print(key)
   print(value['untested_count'])

输出:

Engine
4088
Management Web Console
12067