pythonpygal

Can't get last few countries to show their population on pygal world map


I am working through python crash course and plotting populations on the pygal world map. Some country codes have to retrieved specifically because their country name is not standard. I started to trying to get this non-standard country codes with bolivia and the congo, but both continue to be blank on the pygal map. attached is both relevant modules, any help would be appreciated.

code to get country codes:

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """return the pygal 2-digit country code for
    given country"""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    if country_name == 'Bolivia, Plurinational State of':
        return 'bo'
    elif country_name == 'Congo, the Democratic Republic of the':
        return 'cd'

        #if the country wasnt found, return none
    return None

and then the program that exports it to the pygal map

import json

from pygal.maps.world import World

from pygal.style import RotateStyle

from country_codes import get_country_code

#load the data into a list
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

#build a dictionary of population data
cc_population = {}


#print the 2010 population for each country
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))
        code = get_country_code(country_name)
        if code:
            cc_population[code] = population

#Group the countries into 3 population levels
cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
for cc, pop in cc_population.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop

wm_style = RotateStyle('#994033')
wm = World(style=wm_style)
wm.title = 'World population in 2010, by country'
wm.add('0-10 mil', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)

wm.render_to_file('world_population.svg')

Solution

  • It looks like you are checking for the names of the countries as they are defined in the Pygal world maps module, but should be checking for the names that are used in the json data file.

    For example, assuming that the json file uses the name 'Bolivia' you would need to change that particular comparison to

    if country_name == 'Bolivia':
        return 'bo'
    

    You can identify any other countries that need to be handled this way by adding a print statement before the last return of the function. When you run the program any missing countries will be listed on the console with the specific text you need to check for.

    #if the country wasnt found, return none
    print(country_name)
    return None