Get international phone number prefix from country code in python

Can I use python-phonenumbers or another python library to get the country invocation code from the two letter country code ( ISO 3166-1 alpha-2 )?

The examples in the phonenumbers

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

"US" -> "1"

"GB" -> "44"

"CL" -> "56"

+4


source to share


3 answers


I don't know of any python libs for this, but here's a csv with all ISO 3166-1 alpha-2 codes and their number prefixes, it should be trivial to search 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 went down, but I found a repository with this data (and more) on Github.

+5


source


using the library.

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.

      

Finally:

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 output the calling code from the 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

      

+3


source


Using python-phonenumbers you can use the COUNTRY_CODE_TO_REGION_CODE map which has international dialing codes (int) as keys and country codes (str) as values. You just change your mind and the job is done.
Here's an example (very similar to toast38coza and cgte's answer ):

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 this helps

0


source







All Articles