Python Rest API - 循环遍历字典对象

时间:2016-08-14 14:46:54

标签: python json rest dictionary

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对象。我试过这个,但是这会反复打印出密钥,如何访问父对象和子对象?

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

2 个答案:

答案 0 :(得分:3)

我认为您想使用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)

答案 1 :(得分:1)

请参阅以下示例:

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。你可以使用你认为合适的名字。