简体   繁体   English

Python - 从嵌套字典访问特定项目

[英]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?我需要使用嵌套的 for 循环吗? 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") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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