Get the country id from the name with pycountry
Question:
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
?
Answers:
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'
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.
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
?
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'
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.