[英]Python - Accessing specific items from a 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))}}
我需要編寫一個函數,該函數將輸入國家名稱字符串和這個嵌套字典,並根據所述國家名稱打印/返回值。
我的主要問題是如何根據國家/地區名稱訪問這些數據? 我需要使用嵌套的 for 循環嗎? 就像是-
def search_country(country, nestedD):
yr = nestedD.keys[0]
for year in nestedD:
region = nestedD[region]
for region in year:
country = nestedD[country]
根據指定的任何國家/地區,我需要能夠打印如下內容:
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])
我不會推薦嵌套字典,但如果你真的想要,你可以這樣做:
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)
輸出
Year: 2015
Country: Switzerland
Rank: --
Score: 1.0
Family: 7.6
Health: 0.419
Freedom: 2.318
我真的找不到排名,但我希望這對你有幫助
看起來有點不必要的復雜,但如果你別無選擇,那么你可以使用它。
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.