Python如何访问函数内部字典的特定值供外部比对使用
实现方案
你现有代码中的get_location()函数已经将包含country字段的location_data字典作为返回值返回,只需要在函数外部调用该函数接收返回结果,即可直接提取对应字段值做比对,无需修改原有函数的内部逻辑。
可直接参考如下可运行的调用代码:
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 # 函数外取值与比对逻辑 if __name__ == "__main__": # 调用函数拿到完整位置信息字典 location_result = get_location() # 提取country字段对应取值 current_country = location_result.get("country") # 定义待比对的目标国家名称字符串 target_country_name = "中国" # 执行等值比对 if current_country == target_country_name: print(f"匹配成功,当前IP归属国家为:{target_country_name}") else: print(f"匹配失败,当前IP归属国家为:{current_country},目标国家为:{target_country_name}")
优化提示
- 建议给所有
requests.get请求添加超时参数,比如requests.get(url, timeout=10),避免网络异常时程序长时间无响应 - 建议增加接口请求异常捕获逻辑,处理接口请求失败、返回格式异常的边界场景
- 字符串比对时建议先对两边值做去空格、统一大小写处理,避免因为首尾空格、大小写差异导致判断错误,比如可调整判断逻辑为
(current_country or "").strip() == target_country_name.strip()
内容的提问来源于stack exchange,提问作者SE1822
相关产品推荐
相关产品推荐

