【问题标题】:Python Rest API - looping through dictionary objectPython Rest API - 遍历字典对象
【发布时间】:2016-08-14 14:46:53
【问题描述】:

这里是 Python 新手

我正在查询一个 API 并得到一个这样的 json 字符串:

{
  "human": [
    {
      "h": 310,
      "prob": 0.9588886499404907,
      "w": 457,
      "x": 487,
      "y": 1053
    },
    {
      "h": 283,
      "prob": 0.8738606572151184,
      "w": 455,
      "x": 1078,
      "y": 1074
    },
    {
      "h": 216,
      "prob": 0.8639854788780212,
      "w": 414,
      "x": 1744,
      "y": 1159
    },
    {
      "h": 292,
      "prob": 0.7896996736526489,
      "w": 442,
      "x": 2296,
      "y": 1088
    }
  ]
}

我想出了如何在 python 中获取 dict 对象

json_data = json.loads(response.text)

但我不确定如何遍历 dict 对象。这个我试过了,但是这样反复打印出key,怎么访问父对象和子对象呢?

   for data in json_data:
        print data
        for sub in data:
            print sub

【问题讨论】:

    标签: python json rest dictionary


    【解决方案1】:

    我认为您想使用 iteritems 从字典中获取键和值,如下所示:

    for k, v in json_data.iteritems():
        print "{0} : {1}".format(k, v)
    

    如果您打算递归遍历字典,请尝试以下操作:

    def traverse(d):
        for k, v in d.iteritems():
            if isinstance(v, dict):
                traverse(v)
            else:
                print "{0} : {1}".format(k, v)
    
    traverse(json_data)
    

    【讨论】:

    • 对于 Python 3,使用 .items() 而不是 .iteritems()
    【解决方案2】:

    请参阅以下示例:

    print json_data['human']
    >> [
          {
            "h": 310,
            "prob": 0.9588886499404907,
            "w": 457,
            "x": 487,
            "y": 1053
          },
          {
            "h": 283,
            "prob": 0.8738606572151184,
            "w": 455,
            "x": 1078,
            "y": 1074
          },
          .
          .
      ]
    
    
    for data in json_data['human']:
        print data
    >> {
         "h": 310,
         "prob": 0.9588886499404907,
         "w": 457,
         "x": 487,
         "y": 1053
       } 
    
       {
         "h": 283,
         "prob": 0.8738606572151184,
         "w": 455,
         "x": 1078,
         "y": 1074
        }
    .
    .
    
    
    for data in json_data['human']:
        print data['h']
    >> 310
       283
    

    为了遍历键:

    for type_ in json_data:
        print type_
        for location in json_data[type_]:
            print location
    

    type_ 用于避免 Python 的内置 type。您可以使用任何您认为合适的名称。

    【讨论】:

    • 谢谢,但“关键”可能是不同的类型,例如“车辆”、“人类”、“建筑”等,我如何循环遍历键以及每个键循环遍历位置?抱歉,如果我在最初的问题中不清楚。
    猜你喜欢
    • 2015-09-09
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2012-12-23
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多