我只想打印json文件
import json
from country_codes import get_country_code
filename = 'gdp.json'
with open(filename) as f:
pop_data = json.load(f)
cc_populations = {}
for pop_dict in pop_data:
if pop_dict['Year'] == '1970':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
code = get_country_code(country_name)
if code:
print(code + ": " + str(population))
else:
print('ERROR - ' + country_name)
json文件为here
运行时什么也没发生
答案 0 :(得分:0)
JSON中的年份是整数。
将if pop_dict['Year'] == '1970':
更改为if pop_dict['Year'] == 1970:
工作示例:
pop_data = [{"Country Code": "ARB", "Country Name": "Arab World", "Value": 25760683041.0857, "Year": 1968},{"Country Code": "ARB", "Country Name": "Arab World", "Value": 28434203615.4829, "Year": 1969},{"Country Code": "ARB", "Country Name": "Arab World", "Value": 31385499664.0672, "Year": 1970},]
import json
cc_populations = {}
for pop_dict in pop_data:
if pop_dict['Year'] == 1970:
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
code = (country_name)
if code:
print(code + ": " + str(population))
else:
print('ERROR - ' + country_name)
输出:
阿拉伯世界:31385499664
旁注:Value
已经是浮点数,因此无需强制转换float(pop_dict['Value'])
。