sLau4
sLau4

Reputation: 63

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

I am trying to iterate through a nested dictionary. I want to display all the values associated with the key: "city_name". This is my piece of code.

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))

Each time i try to run it throws the type error. I am not able to figure out where is the value of x becoming an integer?

Any help would be appreciated. Thanks in advance.

Upvotes: 0

Views: 65

Answers (2)

SimfikDuke
SimfikDuke

Reputation: 1148

You are trying to access to whole dict instead of included list of cities "responseDesc"

I think you was going to get somethinkg like this:

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))

Upvotes: 2

user15801675
user15801675

Reputation:

This is what you need. You need to fetch the value using the key.

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

Upvotes: 0

Related Questions