Reputation: 644
Consider the following nested dictionary:
{year: {region: {country: ((val1, val2), (val3, val4))}}}
{2015: {'Europe': {'Switzerland': ((1.0, 7.6), (0.419, 2.318))},
{'Iceland': ((1.2, 3.2), (2.3, 1.00))}}
I need to write a function that taskes as input the country name string, and this nested dictionary, and prints/returns values based on said country name.
My main question is how do I access this data based on country name? Do I need to use nested for loops? something like-
def search_country(country, nestedD):
yr = nestedD.keys[0]
for year in nestedD:
region = nestedD[region]
for region in year:
country = nestedD[country]
Based on whatever country is specified, I need to be able to print something like this:
Year: 2015
Country: Ireland
Rank: 18
Score: 6.94
Family: 1.37
Health: 0.90
Freedom: 0.62
Upvotes: 0
Views: 102
Reputation: 33285
for year in nestedDict:
for region in nestedDict[year]:
if country in nestedDict[year][region]:
print(f'{year} {country} val1:', nestedDict[year][region][country][0][0])
print(f'{year} {country} val2:', nestedDict[year][region][country][0][1])
print(f'{year} {country} val3:', nestedDict[year][region][country][1][0])
print(f'{year} {country} val4:', nestedDict[year][region][country][1][1])
Upvotes: 1
Reputation: 108
Seems a bit unnecessarily complicated but if you have no choice then you can use this.
data = {
2015: {
'Europe':{
'Switzerland': (
(1.0, 7.6),
(0.419, 2.318)
),
'Iceland': (
(1.2, 3.2),
(2.3, 1.00)
)
}
}
}
def get_data(country: str):
for year, regions in data.items():
for region, countries in regions.items():
if country in countries.keys():
stats = countries[country]
print(
"Year: {0}\nCountry: {1}\nRank: {2}\nScore: {3}\nFamily: {4}\nHealth: {5}\nFreedom: {6}\n\n"\
.format(year, country, None, stats[0][0], stats[0][1], stats[1][0], stats[1][1])
)
get_data("Iceland")
Upvotes: 1
Reputation: 118
I wouldn't recomend a nested dictionary but if you really want to, you can do something like this:
d = {2015: {'Europe': {
'Switzerland': {((1.0, 7.6), (0.419, 2.318))},
'Iceland': {((1.2, 3.2), (2.3, 1.00))}
}
}
}
def search_country(selectedCountry, nestedD):
for year,valueYear in d.items():
for continent,countries in valueYear.items():
for country, values in countries.items():
if (country == selectedCountry):
print("Year: ",year,
"\nCountry: ", selectedCountry,
"\nRank: ", "--",
"\nScore: ", list(*values)[0][0],
"\nFamily: ", list(*values)[0][1],
"\nHealth: ", list(*values)[1][0],
"\nFreedom: ",list(*values)[1][1])
search_country('Switzerland', d)
Output
Year: 2015
Country: Switzerland
Rank: --
Score: 1.0
Family: 7.6
Health: 0.419
Freedom: 2.318
I can't really find the Rank, but i hope this helps you
Upvotes: 1