【问题标题】:Python json print key from structurePython json从结构中打印键
【发布时间】:2016-07-05 21:12:51
【问题描述】:

我有这个结构

> api.open_orders(url.api)
[                               # List of open orders
    {
        'id': string,           ## Order ID
        'type': string,         ## Order type - one of
    }, ...
]

我尝试使用 print int(open_o['type']) 进行打印,但不想工作

TheTraceback(最近一次调用最后一次):文件“tr1.py”,第 11 行,在 print int(open_o['type']) TypeError: list indices must be 整数,而不是 str

有人知道如何打印'type'吗?

【问题讨论】:

  • 在您的示例中尝试使用[0]["type"] 而不是["type"] 以获取存储在列表第一个槽(索引为0)的dict 中的类型值。参照。我的回答。

标签: python json


【解决方案1】:

试试:

api.open_orders(url.api)[0]["type"]

回溯告诉您,您有一个列表,您可以在其中使用类型进行索引,因此第一个 dict 嵌套更深一层,作为列表索引 0 处的元素(方括号表示列表和索引操作符是可以的,因为我们在 ASCII 中没有那么多字符可以用作语言标记,但有时会让人恼火)。

【讨论】:

  • 很好,工作!我有这个 api.sell_limit_order(url.api) { 'price': decimal, 'amount': decimal} 如何设置这两个参数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2016-09-07
相关资源
最近更新 更多