I'm planning to build a contact web page where users can select their country and choose a specific region within that country. I need to have the corresponding calling code for each country. To achieve this, I would like to generate a Python dictionary that includes all the necessary information. Here's the desired format I'd like to achieve:

output:

COUNTRY_DATA = {
    "COUNTRY_ID_1": {
        "name": "COUNTRY_NAME_1",
        "calling_code": COUNTRY_NUMBER_1,
        "states": [LIST_COUNTRY_STATES_1]
    },
    "COUNTRY_ID_2": {
        "name": "COUNTRY_NAME_2",
        "calling_code": COUNTRY_NUMBER_2,
        "states": [LIST_COUNTRY_STATES_2]
    },
    "COUNTRY_ID_3": {
        "name": "COUNTRY_NAME_3",
        "calling_code": COUNTRY_NUMBER_3,
        "states": [LIST_COUNTRY_STATES_3]
    },
    ...
}

Could you please assist me in creating the Python dictionary COUNTRY_DATA in the specified format?

Expected output:

COUNTRY_DATA = {
    "US": {
        "name": "United States",
        "calling_code": "+1",
        "states": ["California", "New York", "Texas"]
    },
    "GB": {
        "name": "United Kingdom",
        "calling_code": "+44",
        "states": ["England", "Scotland", "Wales"]
    },
    "CA": {
        "name": "Canada",
        "calling_code": "+1",
        "states": ["Ontario", "Quebec", "British Columbia"]
    },
    ...
}
1

There are 1 best solutions below

0
Milovan Tomašević On

One of the possible solutions is to use python libraries: phonenumbers and pycountry.

The first example prints all values to the console, while the second example creates a python dictionary that can be copied into the code and used.

Example 1:

import pycountry
import phonenumbers

COUNTRY_DATA = {}

for country in pycountry.countries:
    country_code = country.alpha_2
    country_name = country.name

    country_data = {'name': country_name, 'calling_code': '', 'states': []}

    if hasattr(country, 'calling_codes'):
        calling_codes = country.calling_codes
        if calling_codes:
            country_data['calling_code'] = calling_codes[0]
    else:
        try:
            country_data['calling_code'] = phonenumbers.country_code_for_region(country_code)
        except phonenumbers.phonenumberutil.Error:
            pass

    subdivisions = pycountry.subdivisions.get(country_code=country_code)
    if subdivisions:
        country_data['states'] = [subdivision.name for subdivision in subdivisions]

    COUNTRY_DATA[country_code] = country_data

# Alphabetical sorting of the dictionary
sorted_countries = sorted(COUNTRY_DATA.items(), key=lambda x: x[1]['name'])

# Print the generated data for each country
for country_code, country_data in sorted_countries:
    print(f"Country: {country_data['name']}")
    print(f"Calling Code: {country_data['calling_code']}")

    # Sorting states/provinces alphabetically
    sorted_states = sorted(country_data['states'])
    print(f"States/Provinces: {', '.join(sorted_states)}")
    
    print()

Example 2:

import pycountry
import phonenumbers

COUNTRY_DATA = {}

for country in pycountry.countries:
    country_code = country.alpha_2
    country_name = country.name

    country_data = {'name': country_name, 'calling_code': '', 'states': []}

    if hasattr(country, 'calling_codes'):
        calling_codes = country.calling_codes
        if calling_codes:
            country_data['calling_code'] = calling_codes[0]
    else:
        try:
            country_data['calling_code'] = phonenumbers.country_code_for_region(country_code)
        except phonenumbers.phonenumberutil.Error:
            pass

    subdivisions = pycountry.subdivisions.get(country_code=country_code)
    if subdivisions:
        country_data['states'] = sorted([subdivision.name for subdivision in subdivisions])  # Sortiranje provincija

    COUNTRY_DATA[country_code] = country_data

# Alphabetical sorting of the dictionary
sorted_countries = sorted(COUNTRY_DATA.items(), key=lambda x: x[1]['name'])

# Generating an output Python dictionary
output = "COUNTRY_DATA = {\n"
for country_code, country_data in sorted_countries:
    output += f"    '{country_code}': {country_data},\n"
output += "}"

print(output)

The output can be saved directly to a file:

python code.py > const.py