簡體   English   中英

獲取類型錯誤:int 類型的參數在 Python 中不可迭代

[英]Getting Type error : argument of type int is not iteratable in Python

我正在嘗試遍歷嵌套字典。 我想顯示與鍵關聯的所有值:“city_name”。 這是我的一段代碼。

nested_dictionary = {"responseCode": 0,
  "responseDesc": [
    {
      "city_id": 1,
      "city_name": "Mumbai",
      "total_trips": 0
    },
    {
      "city_id": 2,
      "city_name": "Delhi",
      "total_trips": 0
    }
    ]
}
temp = "city_name"

for i in nested_dictionary.keys():
    print(i)
    if i == "responseDesc":
        x = [v[temp] for k, v in nested_dictionary.items() if temp in v]
        print("The extracted values : " + str(x))

每次我嘗試運行它都會拋出類型錯誤。 我無法弄清楚 x 的值在哪里變成整數?

任何幫助,將不勝感激。 提前致謝。

您正在嘗試訪問整個 dict 而不是包含的城市列表“responseDesc”

我想你會得到這樣的想法:

nested_dictionary = {"responseCode": 0,
  "responseDesc": [
    {
      "city_id": 1,
      "city_name": "Mumbai",
      "total_trips": 0
    },
    {
      "city_id": 2,
      "city_name": "Delhi",
      "total_trips": 0
    }
    ]
}
temp = "city_name"

x = [desc[temp] for desc in nested_dictionary['responseDesc'] if temp in desc]
print("The extracted values : " + str(x))

這就是你所需要的。 您需要使用密鑰獲取

x = [v[temp] for v in nested_dictionary[i] if temp in v]
    print("The extracted values : " + str(x))

暫無
暫無

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

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