ColdCoffeeMug
ColdCoffeeMug

Reputation: 168

Cannot extract country code from pygal.maps.world.COUNTRIES

I am trying to write a function which extracts the two-digit country code from pygal.maps.world.COUNTRIES but it does not work consistently. My code:

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
"""Return the Pygal 2-digit country code for the given country"""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        # If the country wasn't found, return None.
        return None

When testing with the following:

print(get_country_code('Andorra'))
print(get_country_code('Afghanistan'))
print(get_country_code('United Arab Emirates'))

I get the results:

ad
None
None

Upvotes: 2

Views: 854

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

This doesn't answer your question directly, but you can just use pycountry to do this easily:

import pycountry

COUNTRIES = ['Andorra', 'Afghanistan', 'United Arab Emirates']

# Get all country mappings, using two digit codes
country_mapping = {country.name: country.alpha_2 for country in pycountry.countries}

# Map your countries
country_codes = [country_mapping.get(country) for country in COUNTRIES]

print(country_codes)
# ['AD', 'AF', 'AE']

Upvotes: 2

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Your for loop always returned after the first iteration, because you got the indentation of return None wrong, so that it was part of the for loop.

This should work:

def get_country_code(country_name):
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    # If the country wasn't found, return None.
    return None

Upvotes: 3

Related Questions