End-To-End Example: European Country Locator

In this example, we will load in json data for European countries. We will write a program to prompt to input a country then tell the user which part of Europe the country is located in and what are the neighboring European countries.


In [ ]:
## todo list
# load europe data into Python
# loop
#   input a country name
#   if country name is quit, exit loop
#   for each country in europe
#        if input name equals country name
#              get info on country (region and neighbors)
#              print country info

In [41]:
import json

# input: none
# output: Python object of data in JSON file
def load_europe_data():    
    with open('ETEE-europe.json', encoding='utf8') as f:
        data = f.read()
        europe = json.loads(data)
        return europe

# input: country and europe data
# output: dictionary of country info (name, region and neighbors)
def extract_country_info(country, europe):
    info = {}
    info['name'] = country['name']
    info['subregion'] = country['subregion']
    info['borders'] = []
    for country_code in country['borders']:
        for country in europe: 
            if country['alpha3Code'] == country_code:
                info['borders'].append(country['name'])
    return info

# main program 
europe = load_europe_data()
print("EUROPEAN COUNTRY LOCATOR")
while True:
    name = input("Enter a country name, or type 'quit': ").title()
    if name == 'Quit':
        break
    for country in europe:
        if name == country['name']:
            info = extract_country_info(country, europe)
            print("%s is in %s.\nBordering countries are %s" % (info['name'], info['subregion'], info['borders']))


European country locator.
Enter a country name, or type 'quit': Norway
Norway is in Northern Europe.
Bordering countries are ['Finland', 'Sweden', 'Russia']
Enter a country name, or type 'quit': Finland
Finland is in Northern Europe.
Bordering countries are ['Norway', 'Sweden', 'Russia']
Enter a country name, or type 'quit': Russia
Russia is in Eastern Europe.
Bordering countries are ['Belarus', 'Estonia', 'Finland', 'Latvia', 'Lithuania', 'Norway', 'Poland', 'Ukraine']
Enter a country name, or type 'quit': Poland
Poland is in Eastern Europe.
Bordering countries are ['Belarus', 'Czech Republic', 'Germany', 'Lithuania', 'Russia', 'Slovakia', 'Ukraine']
Enter a country name, or type 'quit': quit