i execute a url request substituting values into it and get data in the following format
{'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 (lack of value in the url) I save the value None, but I get the error 'list index out of range'
json.get('result', {}).get('list', {})[0].get('lastPrice')
CodePudding user response:
There are 3 problems I can see:
- Don't use json as a variable name because it's a standard lib
- You look for the first element of a list which can be empty
- Your second 'get' return a dictionary if there is no key called 'list' in the dictionary 'result'.
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')
CodePudding user response:
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'