[英]How to fix Dictionary get() Method in python 'list index out of range'
我执行一个 url 请求,将值代入其中并获取以下格式的数据
{'retCode': 0, 'retMsg': 'OK', 'result': {'category': 'linear', 'list': [{'symbol ': 'XRPUSDT', 'bidPrice': '0.4089'}]}}
我需要从中获取出价,我使用get()
方法,以便在出现错误时使用
(网址中缺少价值)
我保存值 None,但出现错误
列表索引超出范围
json.get('result', {}).get('list', {})[0].get('lastPrice')
我可以看到 3 个问题:
这是一个解决方案:
def get_bid_price(json_returned):
result_list = json_returned.get('result', {}).get('list', [{}])
if result_list:
return result_list[0].get('bidPrice')
根据您可能想要的问题中显示的字典结构:
print(_dict.get('result', {}).get('list', [{}])[0].get('lastPrice'))
注意获取“列表”时对默认值的更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.