Matt
Matt

Reputation: 4989

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"

Upvotes: 7

Views: 10915

Answers (4)

Skippy le Grand Gourou
Skippy le Grand Gourou

Reputation: 7694

The phonenumbers library actually has (as of version 8.10.5 at least) a country_code_for_region() function :

>>> import phonenumbers
>>> phonenumbers.country_code_for_region("GB")
44

Upvotes: 6

cgte
cgte

Reputation: 450

using the lib.

In [1]: from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

In [2]: COUNTRY_CODE_TO_REGION_CODE
Out[2]: 
{1: ('US',
     'AG',
     'AI',

....
 7: ('RU', 'KZ'),
 20: ('EG',),
 27: ('ZA',),
 30: ('GR',),
 31: ('NL',),
 32: ('BE',),
 33: ('FR',),
 34: ('ES',),
 36: ('HU',),
 39: ('IT', 'VA'),
 40: ('RO',),
 ... snip.

Eventually :

from phonenumbers import COUNTRY_CODE_TO_REGION_CODE, REGION_CODE_FOR_NON_GEO_ENTITY
REGION_CODE_TO_COUNTRY_CODE = {}

for country_code, region_codes in COUNTRY_CODE_TO_REGION_CODE.items():
    for region_code in region_codes:
        if region_code == REGION_CODE_FOR_NON_GEO_ENTITY:
            continue
        if region_code in REGION_CODE_TO_COUNTRY_CODE:
            raise ValueError("%r is already in the country code list" % region_code)
        REGION_CODE_TO_COUNTRY_CODE[region_code] = str(country_code)

The following function will give you the calling code from a provided iso code:

def get_calling_code(iso):
  for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
    if iso.upper() in isos:
        return code
  return None

Which gives you:

get_calling_code('US')
>> 1
get_calling_code('GB')
>> 44

Upvotes: 9

GianAnge
GianAnge

Reputation: 633

Using python-phonenumbers you can exploit the COUNTRY_CODE_TO_REGION_CODE map, it is a dict having international calling codes (int) as key and country codes (str) as values. You just reverse the dict and the work is done.
Here an example (very similar to the answer of toast38coza and cgte):

REGION_CODE_TO_COUNTRY_CODE = {}
for k, vs in phonenumbers.COUNTRY_CODE_TO_REGION_CODE.items(): # prefix -> country code: 39 -> 'IT'
    for v in vs:   #because a prefix could belong to more countries
       REGION_CODE_TO_COUNTRY_CODE[v] = k # country code-> prefix : 'IT' -> 39# now you have your reversed map

print( 'Italy country prefix: +'+ str( REGION_CODE_TO_COUNTRY_CODE['IT'] ) )

Hope it will help

Upvotes: 0

L3viathan
L3viathan

Reputation: 27283

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.

Upvotes: 8

Related Questions