挑选出Python字典的嵌套组件

kh_*_*one 0 python json

我有一个JSON格式的API response,当我使用时将其转换为字典时,格式如下json.loads(response)

{
  "stories" : [
    {
      "headline" : "some text",
      "summary" : [
        "some more text"
      ],
      "texts" : [ 
        {
          "title" : "even more text",
          "id" : "a number"
        },
        {
          "title" : "more text",
          "id" : "another number"
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

让我们称这本字典dict

我可以访问stories使用dict['stories']。但是我该如何使用summary钻头?

我以为我可以做,dict['stories']['summary']但这会引发错误list indices must be integers or slices, not str

Poo*_*jan 5

  • 因为你stories是一个list

    做这个

dict['stories'][0]['summary']
Run Code Online (Sandbox Code Playgroud)

PS:一个技巧不要dict用作变量。keywords用作的错误做法variables。您会遇到一些问题,这些问题会在晚上困扰您。:)