guiguilecodeur
guiguilecodeur

Reputation: 457

Get the country id from the name with pycountry

I try to get the country id when I give the country's name.

import pycountry

pays = "france"

initales_pays = pycountry.countries.search_fuzzy(pays)
print(initales_pays)

And the result is

[Country(alpha_2='FR', alpha_3='FRA', name='France', numeric='250', official_name='French Republic')]

How can I take the alpha_2?

Upvotes: 0

Views: 796

Answers (2)

Tobias Herrmann
Tobias Herrmann

Reputation: 81

The accepted answer is correct. However pycountry is quite slow which can be an issue when dealing with large datasets. There is a faster library called countrywrangler.

Here's an example code using CountryWrangler:

import countrywrangler as cw

input_countries = ['American Samoa', 'Canada', 'France']

codes = [cw.Normalize.name_to_alpha2(country) for country in input_countries]

print(codes)  # prints ['AS', 'CA', 'FR']

Full documentation: https://countrywrangler.readthedocs.io/en/latest/normalize/country_name/

Disclosure: I am the author of countrywrangler.

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23140

According to the examples shown on the pycountry page on PyPI, the properties of a Country instance can be accessed as attributes.

In your case this would be:

country = initales_pays[0]
country.alpha_2  # 'FR'

Upvotes: 2

Related Questions