简体   繁体   English

如何修复 python 中的字典 get() 方法“列表索引超出范围”

[英]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 个问题:

  1. Don't use json as a variable name because it's a standard lib不要使用 json 作为变量名,因为它是标准库
  2. You look for the first element of a list which can be empty您寻找可以为空的列表的第一个元素
  3. 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')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM