Пример #1
0
#将数据加载到一个列表中
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

#创建一个字典存储国别码和人口数量
cc_populations = {}

for pop_dict in pop_data:
    #遍历pop_data中的每个元素,每个元素都是一个字典,包含四个键值对
    if pop_dict['Year'] == '2010':
        country = pop_dict['Country Name']
        #人口数据是字符串,先转换成浮点数,再转换成整形。int会丢掉浮点数的小数部分
        population = int(float(pop_dict['Value']))
        code = get_country_code(country)
        if code:
            #如果返回了国别码,就将国别码和人口数量分别作为键和值填充字典
            cc_populations[code] = population

#根据人口数量将所有的国家分成三组
cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
#遍历cc_populations,检查每个国家人口的数量,进行人口数量分组
for cc, pop in cc_populations.items():
    #cc国别码,pop人口数量。将每个国别码-人口数量对加入到合适的字典
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop
Пример #2
0
from pygal.style import LightColorizedStyle
from country import get_country_code
from pygal.maps.world import World

#Load the data into a list
filename = "data_json.json"
with open(filename) as f:
    population_data = json.load(f)

#Create a dictionary of populations
populations = {}
for pop_dictionary in population_data:
    if pop_dictionary["Year"] == 2015:
        country_name = pop_dictionary["Country Name"]
        population = pop_dictionary["Value"]
        code = get_country_code(country_name)
        
        #Some countries don't have a country code
        if code:
            populations[code] = population
    
#Seperating the countries into 3 different population levels for better visuals
population_1, population_2, population_3 = {},{},{}

for country,population in populations.items():
    if population < 10000000:
        population_1[country] = population
    elif population < 1000000000:
        population_2[country] = population
    else:
        population_3[country] = population