Python Forum

Full Version: Phone numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone

I am trying to use phone-iso3166, phonenumbers and pycountries to create on the fly dictionaries of countries with the corresponding international phone code. Can anyone give me an example where I will input a country and I get the international phone code? Or at least where can I see all the attributes so that I can experiment?
I found this example

<code>
>>>from phone_iso3166.country import *
>>>phone_country(45)
'DK'
</code>

can anyone tell me how to do the exact opposite? Give the two or three (even better for me) letter code for the country and get as output the international phone code?

Thank you in advance for the help
Output:
Signature: phone_iso3166.country.country_prefixes() Docstring: Function that return a dictionary, with an ISO-3166-1 alpha-2 code, as the key, and the country prefix as the value. For countries with multiple prefixes, an abitrary one of them is chosen, for United states and Canada code is denoted as 1. File: c:\users\admin\appdata\local\programs\python\python38\lib\site-packages\phone_iso3166\country.py Type: function
from phone_iso3166 import country

country2number = country.country_prefixes()
# exchanging keys with values
number2country = {value: key for key, value in country2number.items()}
The function country.phone_country() returns the alpha2 for the number prefix.
The function country.country_prefix() does the inverse. There you get the number prefix of one country.

If you do the trick with exchanging keys <-> values, then keep in mind, that repeating values are overwritten. The last occurrence wins.
Also, if you want more that just country code, there's the CIA FWorld Factbook https://www.cia.gov/library/publications...-factbook/
from this page, you can select country (pulldown, upper right) and obtain a plethora of information about it.