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

后端 未结 7 1136
醉酒成梦
醉酒成梦 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:11

    You can use this csv file : country code list into a CSV.

    import csv
    
    dic = {}
    with open("wikipedia-iso-country-codes.csv") as f:
        file= csv.DictReader(f, delimiter=',')
        for line in file:
            dic[line['English short name lower case']] = line['Alpha-2 code']        
    
    countries = ['American Samoa', 'Canada', 'France']
    
    for country in countries:
        print(dic[country])
    

    Will print:

    AS
    CA
    FR
    

    Few more alternatives.

提交回复
热议问题