Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pycountry | extract values or convert Country object to iterable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading