VIBHU BAROT
VIBHU BAROT

Reputation: 367

Get continent name from country using pycountry

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', ....]

Upvotes: 19

Views: 41580

Answers (3)

Roman Alexandrovich
Roman Alexandrovich

Reputation: 350

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',
    'EU': 'Europe'
}

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 Antarctica continent ¯_(ツ)_/¯

Upvotes: 7

Isra Mata
Isra Mata

Reputation: 151

All the tools you need are provided in pycountry-convert.

Here is an example of how you can create your own function to make a direct conversion from country to continent name, using pycountry's tools:

import pycountry_convert as pc

def country_to_continent(country_name):
    country_alpha2 = pc.country_name_to_country_alpha2(country_name)
    country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
    country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code)
    return country_continent_name

# Example
country_name = 'Germany'
print(country_to_continent(country_name))

Out[1]: Europe 

Hope it helps!

Remember you can access function descriptions using '?? function_name'

?? pc.country_name_to_country_alpha2

Upvotes: 15

Oliver H. D.
Oliver H. D.

Reputation: 333

Looking at the documentation, would something like this do the trick?:

country_alpha2_to_continent_code()

It converts country code(eg: NO, SE, ES) to continent name.

If first you need to acquire the country code you could use:

country_name_to_country_alpha2(cn_name, cn_name_format="default")

to get the country code from country name.

Full example:

import pycountry_convert as pc

country_code = pc.country_name_to_country_alpha2("China", cn_name_format="default")
print(country_code)
continent_name = pc.country_alpha2_to_continent_code(country_code)
print(continent_name)

Upvotes: 10

Related Questions