简体   繁体   中英

Python - Accessing specific items from a nested dictionary

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM