我想獲取 location_data['country'] 的鍵值并將其與函式外的字串值(國家名稱)進行比較。
import requests
def get_ip():
response = requests.get(
'https://api64.ipify.org?format=json').json()
return response["ip"]
def get_location():
ip_address = get_ip()
response = requests.get(
f'https://ipapi.co/{ip_address}/json/').json()
location_data = {
"ip": ip_address,
"city": response.get("city"),
"region": response.get("region"),
"country": response.get("country_name")
}
return location_data
uj5u.com熱心網友回復:
只需在呼叫 get_location 函式后進行比較即可。
location_data = get_location()
if location_data.get('country') == 'country_string':
pass
在 dict 中查找鍵的值時嘗試使用 get 方法,否則,如果鍵不存在,您可能會遇到 KeyError。
uj5u.com熱心網友回復:
不會吧get_location()['country'] == 'string value' ?
uj5u.com熱心網友回復:
看來您可能不熟悉 return 的作業原理。
由于您要回傳字典,因此您可以將其存盤在變數中并訪問它。
location_data = get_location()
if location_data['country'] == "whateverstring":
#Do whatever here
基本上,您將函式回傳的內容存盤在一個變數中,在這種情況下,該變數是位置資料的字典,您可以在函式外部訪問它。
Ramintafromlt 還提供了一種方法,您可以直接比較該特定鍵的值,而不是將函式回傳的內容存盤在變數中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496485.html
