Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 phonenumbers 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"

like image 542
Matt Avatar asked Apr 20 '15 21:04

Matt


1 Answers

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

edit: The above link has gone down, but I've found a repository with that data (and more) on Github.

like image 190
L3viathan Avatar answered Oct 13 '22 12:10

L3viathan