[英]How to fix Dictionary get() Method in python 'list index out of range'
I execute a url request substituting values into it and get data in the following format我执行一个 url 请求,将值代入其中并获取以下格式的数据
{'retCode': 0, 'retMsg': 'OK', 'result': {'category': 'linear', 'list': [{'symbol ': 'XRPUSDT', 'bidPrice': '0.4089'}]}}
and I need to get bidprice from it, I use the get()
method so that in case of an error我需要从中获取出价,我使用
get()
方法,以便在出现错误时使用
(lack of value in the url)
(网址中缺少价值)
I save the value None, but I get the error我保存值 None,但出现错误
list index out of range
列表索引超出范围
json.get('result', {}).get('list', {})[0].get('lastPrice')
There are 3 problems I can see:我可以看到 3 个问题:
Here is a solution:这是一个解决方案:
def get_bid_price(json_returned):
result_list = json_returned.get('result', {}).get('list', [{}])
if result_list:
return result_list[0].get('bidPrice')
On the basis of the dictionary structure shown in the question you probably want:根据您可能想要的问题中显示的字典结构:
print(_dict.get('result', {}).get('list', [{}])[0].get('lastPrice'))
Note the change to the default when getting 'list'注意获取“列表”时对默认值的更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.