【问题标题】:How to access dict inside list如何访问列表中的字典
【发布时间】:2022-12-13 09:39:48
【问题描述】:

我搜索了类似的问题但没有运气。 我正在尝试在“出价”和“要价”下获取 a 内的数据。 这是代码:

response = requests.get(book_url, params={'instrument_name': 'BTC_USDT', 'depth': 2})
resp = response.json()
print('resp: ', type(resp))
a  = resp['result']['data']

这是一个样子:

[{'bids': [['17015.36', '1.86922', '6'], ['17014.91', '0.01175', '1']],
  'asks': [['17015.37', '0.98410', '3'], ['17015.54', '0.01469', '1']],
  't': 1670869985838}]

如果我尝试获取“出价”,我会收到以下错误:

a['bids']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[102], line 1
----> 1 a['bids']

TypeError: list indices must be integers or slices, not str

我究竟做错了什么?

【问题讨论】:

  • 变量a 包含一个列表,所以你必须这样做:a[0]['bids']

标签: python list api dictionary


【解决方案1】:

a 是一个 list,其中一个元素是您想要的 dict

a['bids'] 要求一个字典键为 'bids' 的元素。

试试a[0]['bids']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多