嵌套Python3字典出现问题 [英] Having trouble with nested Python3 dictionary

查看:58
本文介绍了嵌套Python3字典出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Service Now Rest API检索服务器上的信息,该服务器将作为JSON响应返回,并将其解码为python3字典,因此我可以在代码中进一步提取特定项,但是我有难以理解如何使用从JSON创建的嵌套字典.有人可以帮我了解如何从字典中提取特定值.参见下面的示例(返回)(返回).

I am using the Service Now Rest API to retrieve information on a server which is being returned as a JSON response which I am decoding into a python3 dictionary so I can pull out specific items further down in my code, but I am having trouble understanding how to use what appears to be a nested dictionary that is created from the JSON. Can someone please help me understand how to extract specific values from the dictionary. See below an example of what comes back (shortened).

#! /usr/bin/python3

# Include required libraries
import requests

# Set the request parameters
url = 'https://example.service-now.com/api/now/table/cmdb_ci_server'
user = 'example'
pwd = 'example'

# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}

# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )

# Check for HTTP codes other than 200
if response.status_code != 200:
    print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
    exit()

# Decode the JSON response into a dictionary and use the data
data = response.json()

print(data)

以下是响应示例(缩短了)

Here is an example of the response (shortened)

{
  "result": [
    {
      "u_raid": "",
      "u_pir_required": "false",
      "u_original_system": "",
      "u_backup_pool": "vsdfnvjsv",
      "u_virtual_ip": "",
      "cpu_speed": "",
      "u_vendor": "",
      "u_lun_tier": "",
      "cost_center": {
        "link": "cdncdnckidnicsw",
        "value": "vfevfdbvfdsbvsdf"
      },
      "dns_domain": "",
      "u_vio2": "",
      "fault_count": "0",
      "u_hardware_type": "",
      "host_name": ""
    }
  ]
}

在阅读了一些嵌套词典教程之后,我尝试了以下方法,但是我运气不高.

I have tried the following after working through a few nested dictionary tutorials, but I am not having much luck.

print(data['result']['u_backup_pool'])

TypeError:列表索引必须是整数或切片,而不是str

TypeError: list indices must be integers or slices, not str

推荐答案

'result'的值是一个列表(请注意方括号),其中包含一项,请尝试 print(数据['结果'] [0] ['u_backup_pool'])

The value for key 'result' is a list (notice the square brackets) with one item, try print(data['result'][0]['u_backup_pool'])

这篇关于嵌套Python3字典出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆