【问题标题】:iterating through a json object/dictionary [closed]遍历 json 对象/字典 [关闭]
【发布时间】:2017-05-06 00:54:49
【问题描述】:
abc = {
"orders": [
    {
        "orderID": 5,
        "cost": 10,
        "sell": 15
    },
    {
        "orderID": 6,
        "cost": 8,
        "sell": 12
    },
    {
        "orderID": 7,
        "cost": 15,
        "sell": 26           
        }
    ]
}

for key, value in abc.items():
print (value["orderID"])

我正在尝试提取 orderID 值,但似乎无法完成这项工作。它应该回应 5,6,7

【问题讨论】:

  • 首先打印value,然后看看它返回了什么......

标签: python json loops dictionary iteration


【解决方案1】:

现在您正在循环遍历 abc 字典。相反,你想循环 abc['orders']:

for order in abc['orders']:
    print (order["orderID"])

【讨论】:

  • 您确定您的代码与您的陈述相符吗? ;)
  • 哎呀,真是太愚蠢了……谢谢
  • 工作!!!谢谢
  • 太棒了。如果您的问题得到解决,您应该接受其中一个答案。
【解决方案2】:
for d in abc['orders']:
    print (d["orderID"])

abc 有一个键 orders 这是一个列表。因此您可以遍历该列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 2013-01-21
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多