Last modified: Sep 20, 2023 By Alexander Williams
Python Country Code Examples
Example 1: Telephone Country Code Lookup
def get_country_code(country_name):
country_codes = {
"United States": "+1",
"United Kingdom": "+44",
"Canada": "+1",
"Australia": "+61"
# Add more country codes as needed
}
return country_codes.get(country_name, "Country code not found")
# Example usage:
print(get_country_code("United States")) # Output: +1
print(get_country_code("Germany")) # Output: Country code not found
Example 2: ISO Country Code Lookup
def get_iso_country_code(country_name):
iso_country_codes = {
"United States": "US",
"United Kingdom": "GB",
"Canada": "CA",
"Australia": "AU"
# Add more ISO country codes as needed
}
return iso_country_codes.get(country_name, "ISO code not found")
# Example usage:
print(get_iso_country_code("Canada")) # Output: CA
print(get_iso_country_code("France")) # Output: ISO code not found
Example 3: Country Codes in a List
country_codes = {
"US": "United States",
"GB": "United Kingdom",
"CA": "Canada",
"AU": "Australia"
# Add more ISO country codes and country names as needed
}
# Example: Print a list of ISO codes and corresponding country names
for iso_code, country_name in country_codes.items():
print(f"{iso_code}: {country_name}")
# Output:
# US: United States
# GB: United Kingdom
# CA: Canada
# AU: Australia
Example 4: Using pycountry to Get ISO Country Codes and Names
import pycountry
# Function to get ISO country code by country name
def get_iso_country_code(country_name):
try:
country = pycountry.countries.get(name=country_name)
return country.alpha_2 if country else "ISO code not found"
except LookupError:
return "ISO code not found"
# Example usage:
print(get_iso_country_code("Canada")) # Output: CA
print(get_iso_country_code("Germany")) # Output: DE
print(get_iso_country_code("Nonexistent Country")) # Output: ISO code not found