pycountry | extract values or convert Country object to iterable

619 Views Asked by At

How can I extract values in Country object or convert to an iterable?

Maybe specicially this isn't possible.

Goal: lookup a country code using alpha_2 param and extract all values.


Usage

pip install pycountry
import pycountry

pycountry.countries.get(alpha_2='DE')
>>> Country(alpha_2='DE', alpha_3='DEU', flag='', name='Germany', numeric='276', official_name='Federal Republic of Germany')

Attempt

list(pycountry.countries.get(alpha_2='DE'))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-5d8d83cf3b5c> in <module>
----> 1 list(pycountry.countries.get(alpha_2='DE'))

TypeError: 'Country' object is not iterable
1

There are 1 best solutions below

0
On BEST ANSWER

get() is correct, but you don't convert it into a list. You can get hold of the country with .get() and a known attribute, then use dot notation to get the other attributes. E.g.: country = pycountry.countries.get(alpha_2='DE') then country.name will get you 'Germany', country.alpha_3 will get you the alpha3 code for Germany (which is 'DEU'), etc.