Reputation: 1201
This question seem abit weird as I know dictionary are not intended to be used based on values rather than keys I recently came across certain problem to minimize the form fill up procedure as If certain country cities are provided then I need to autocomplete country and continent for that user. I got following Json for my reference .
[{
"Asia": {
"Japan": [
"tokyo",
"hirohima",
]
}
},
{
"Europe": {
"England": [
"Manchester",
"London",
"South gate",
]
}
}
]
Suppose user City is London Can I get England and Europe as Output? or Is my json formating wrong?
Upvotes: 0
Views: 133
Reputation: 77347
You could create a reverse index of city to country/region tuples. Since city names are not unique, you may have the same city name in multiple countries. You could solve this by indexing to a list of country/regions. You would do this once when you get the data and then its available for quick lookup when needed.
from collections import defaultdict
data = [{
"Asia": {
"Japan": [
"tokyo",
"hirohima",
]
}
},
{
"Europe": {
"England": [
"Manchester",
"London",
"South gate",
]
}
}
]
reverse_index = defaultdict(list)
for region_dict in data:
for region, country_dict in region_dict.items():
for country, city_list in country_dict.items():
for city in city_list:
reverse_index[city].append((region, country))
for city, refs in reverse_index.items():
print(city, refs)
Upvotes: 1
Reputation: 23146
You could loop through the data and "reverse engineer" the dictionary:
city = "London"
for d in data:
for continent, countries in d.items():
for country, cities in countries.items():
if "London" in cities:
print(country, continent)
Upvotes: 1
Reputation: 113
to get country name and continent name your json file must be in this form :
[{"ContinentName":"Asia","country":{"countryName":"Japan","cities":["tokyo","hirohima"]}},{"ContinentName":"Europe","country":{"countryName":"England","cities":["london","south gate","Manchester"]}}]
Upvotes: 1