import json#导入模块json,便于正确的加载json格式中的数据
filename = 'population_data.json'
with open(filename) as f:
pop_data=json.load(f)#将数据储存到pop data中
for pop_dict in pop_data:#遍历从pop data中的元素,每一个元素其实都是一个字典,包含四个键值对,将每个字典传给pop dict储存
if pop_dict['Year']=='2010':#检查判断键为Year对应的值是2010时,
country_name = pop_dict['Country Name']#把字典中Country Name的值传给country_name
population = pop_dict['Value']#把字典中Value的值传给population
print(country_name+":"+population)#根据传输的值,打印出来
输出内容
Arab World:357868000
Caribbean small states:6880000
East Asia & Pacific (all income levels):2201536674
East Asia & Pacific (developing only):1961558757
Euro area:331766000
--snip--
West Bank and Gaza:4152000
Yemen, Rep.:24053000
Zambia:12927000
Zimbabwe:12571000
Process finished with exit code 0
import json#导入模块json,便于正确的加载json格式中的数据
filename = 'population_data.json'
with open(filename) as f:
pop_data=json.load(f)#将数据储存到pop data中
for pop_dict in pop_data:#遍历从pop data中的元素,每一个元素其实都是一个字典,包含四个键值对,将每个字典传给pop dict储存
if pop_dict['Year']=='2010':#检查判断键为Year对应的值是2010时,
country_name = pop_dict['Country Name']#把字典中Country Name的值传给country_name
population = int(float(pop_dict['Value']))#把字典中Value的值转化为浮点数在转化整数型传给population,
print(country_name+":"+str(population))#根据传输的值,打印出来,str是字符串格式
执行代码
from pygal.i18n import COUNTRIES
for country_code in sorted(COUNTRIES.keys()):
print(country_code,COUNTRIES[country_code])
会报错
ModuleNotFoundError: No module named ‘pygal.i18n’
因为现在pygal中已经没有i18n,要改用pygal_maps_world.i18n,
在CMD中运行
pip3 install pygal_maps_world
问题即可解决,
执行代码替换为
from pygal_maps_world.i18n import COUNTRIES
for country_code in sorted(COUNTRIES.keys()):#按照字母顺序遍历
print(country_code,COUNTRIES[country_code])#按照遍历的先后顺序,打印出来
执行结果
ad Andorra
ae United Arab Emirates
af Afghanistan
al Albania
am Armenia
--snip--
zw Zimbabwe
网友评论