Skip to content

Instantly share code, notes, and snippets.

@mayankdawar
Created August 7, 2020 20:52
Show Gist options
  • Save mayankdawar/e9d7ab236cd92e4b7d2307f77e679274 to your computer and use it in GitHub Desktop.
Save mayankdawar/e9d7ab236cd92e4b7d2307f77e679274 to your computer and use it in GitHub Desktop.
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 i in nested_d:
temp = nested_d[i]['USA']
US_count.append(temp)
@hadrocodium
Copy link

hadrocodium commented Oct 26, 2021

Using list comprehension reduces the code to one line.

US_count = [nested_d[i]['USA'] for i in nested_d]

But pylint does not like the code above. It prefers the usage of .items() method.

US_count = []

for olympics, country_medal in nested_d.items():
    for country, medal in country_medal.items():
        if country == "USA":
            US_count.append(medal)

Or the use of the list comprehension.

US_count = [
    medal
    for olympics, country_medal in nested_d.items()
    for country, medal in country_medal.items()
    if country == "USA"
    ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment