Reputation: 63
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
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
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