Matt Matt - 10 months ago 98
Python Question

get a phone number's international prefix from a country code in python

Is it possible to use python-phonenumbers or another python lib to get a country calling code from a two letter country code (ISO 3166-1 alpha-2)?

The examples in the

lib focus on extracting a country code from a number, but I'd like to do the opposite, something like:

"US" -> "1"

"GB" -> "44"

"CL" -> "56"

Answer Source

I don't know of any python lib for this, but here's a csv with all ISO 3166-1 alpha-2 codes and their number prefixes, it should be trivial to look it up from there:

import csv

country_to_prefix = {}

with open("countrylist.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        country_to_prefix[row["ISO 3166-1 2 Letter Code"]] = row["ITU-T Telephone Code"]

print country_to_prefix["US"] # +1
print country_to_prefix["GB"] # +44
print country_to_prefix["CL"] # +56