简体   繁体   中英

Python: List inside a Dict?

From this example, how do I get the IP address from the response?

import requests

URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"

session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()

print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)

IP = r['Answer'][-1]
print("IP:", IP)  

Output:

Type: <class 'dict'>
Len: 8
Content: {'Status': 0, 'TC': False, 'RD': True, 'RA': True, 'AD': False, 'CD': False, 'Question': [{'name': 'test.com', 'type': 1}], 'Answer': [{'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}]}
IP: {'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}

Like this?:

IP = r['Answer'][-1]['data']
print("IP:", IP)

Output:

IP: 69.172.200.235

The reply is:

r['Answer'][0]['data']

But I would like to give you a tip on how you could find this.

I like to use the code module to run an interactive console inside my script:

import requests
import code

URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"

session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()

print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)

code.interact(banner="after get request", locals=locals()) #interactive console is created here

IP = r['Answer'][-1]
print("IP:", IP)  

From there, you can play with local variables and test until you find what you need.

I hope that will helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM