Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (45.3k points)

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}}

Here is what I am doing:

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)

I expect the output [35,36,46] but the actual output is ['USA', 'USA', 'USA'] please help me solve this problem

1 Answer

0 votes
by (16.8k points)

You have not append the USA count, you have simply mentioned "USA" in the if statement, use "for country in nested and then USA in your if country variable"

Here is the code for it:

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)

Which will further give your desired output.

Browse Categories

...