How to convert country names to ISO 3166-1 alpha-2 values, using python

后端 未结 7 1135
醉酒成梦
醉酒成梦 2020-12-13 13:25

I have a list of countries like:

countries=[\'American Samoa\', \'Canada\', \'France\'...]

I want to convert them like this:



        
7条回答
  •  失恋的感觉
    2020-12-13 14:03

    There is a module called pycountry.

    Here's an example code:

    import pycountry
    
    input_countries = ['American Samoa', 'Canada', 'France']
    
    countries = {}
    for country in pycountry.countries:
        countries[country.name] = country.alpha_2
    
    codes = [countries.get(country, 'Unknown code') for country in input_countries]
    
    print(codes)  # prints ['AS', 'CA', 'FR']
    

提交回复
热议问题