簡體   English   中英

Python Rest API-遍歷字典對象

[英]Python Rest API - looping through dictionary object

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

我認為您想使用迭代項從字典中獲取鍵和值,如下所示:

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)

請參閱以下示例:

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 您可以使用任何合適的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM