从循环中提取嵌套字典的数据

2024-04-25 08:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

Given the dictionary, nested_d, save the medal count for the USA from all three Olympics in the dictionary to the list US_count

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}
US_count = []

for nested in nested_d:
    # print(nested)
    for country in nested_d[nested]:
            if "USA" in country:
                    US_count.append(country)

print(US_count)

我期望输出[35,36,46],但实际输出是['USA', 'USA', 'USA'] 请帮我解决这个问题


Tags: theinfordictionarycountcountrygivennested
3条回答
nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}

res = [nested_d[host]['USA'] for host in nested_d]

print(res)

输出

^{pr2}$

你也可以试试这个:

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}
US_count = []

for nested in nested_d:
    for country in nested_d[nested]:
            if country=="USA":
                    US_count.append(nested_d[nested][country])

print(US_count)

输出:

^{pr2}$

您应该附加nested_d[nested][country]以获取值。在

相关问题 更多 >

    热门问题