Get continent name from country using pycountry

VIBHU BAROT picture VIBHU BAROT · Apr 29, 2019 · Viewed 13.3k times · Source

How to convert continent name from country name using pycountry. I have a list of country like this

country = ['India', 'Australia', ....]

And I want to get continent name from it like.

continent = ['Asia', 'Australia', ....]

Answer

Roman Alexandrovich picture Roman Alexandrovich · Apr 29, 2019
from pycountry_convert import country_alpha2_to_continent_code, country_name_to_country_alpha2

continents = {
    'NA': 'North America',
    'SA': 'South America', 
    'AS': 'Asia',
    'OC': 'Australia',
    'AF': 'Africa',
}
countries = ['India', 'Australia']

[continents[country_alpha2_to_continent_code(country_name_to_country_alpha2(country))] for country in countries]

Don't know what to do with Antarctida ¯_(ツ)_/¯