python:如何输入储存字典并输出

【问题描述】

存储国家GDP的字典结构如下:

GDP = {

'USA': 95,

'China': 80,

'Japan': 50

}

题目要求:
1、请从标准输入录入多个国家的名字和对应的GDP,存入GDP字典中。(字典不为空)
2、获取所有的key值,存储在列表里
3、获取所有的value值,存储在列表里
4、判断 键'India' 是否在字典中
5、获得字典里所有value 的和

样例输入:

USA 95

China 80

Japan 50

ok

【样例输出】

['China', 'Japan', 'USA']

[50, 80, 95]

no

225

【样例说明】
输入为多行,分别是以空格分隔开的国家和对应的GDP值,以"ok"结束
输出第一行:所有的key值,存储在列表里,升序排列
输出第二行:所有的value值,存储在列表里,升序排列
输出第三行:判断 键'India' 是否在字典中,是输出'yes',否输出'no'
输出第四行:字典里所有value 的和

GDP = {}
while True:
input_str = input()
if input_str == 'ok':
break
k, v = input_str.split(' ')
GDP[k] = int(v)

dict_keys = list(GDP.keys())
dict_values = list(GDP.values())
dict_keys.sort()
dict_values.sort()
print(dict_keys)
print(dict_values)
print('yes' if 'India' in dict_keys else 'no')
print(sum(dict_values))

绘制中国历年 GDP 情况直方图


import json

import pygal

filename = 'gdp.json'

with open(filename) as f:

gdp = json.load(f)

china_gdp = []

year_list = []

for gdp_dict in gdp:

if gdp_dict['Country Name'] == 'China':

year = gdp_dict['Year']

value = gdp_dict['Value']

year_list.append(int(year))

china_gdp.append(int(float(value)))

hist = pygal.Bar()

hist.title = 'Chinese GDP from '+str(year_list[0])+' to '+str(year_list[-1])+''

hist.x_labels = year_list

hist.x_title = 'Year'

hist.y_title = 'GDP (dollars)'

hist.add('Chinese GDP',china_gdp)

hist.render_to_file(hist.title+'.svg')

GDP年增长率

#GDP增长率

num = len(china_gdp)

zero = [0 for count in range(0,num-1)]

growth_rate = [int(10000*(china_gdp[count+1] - china_gdp[count])/china_gdp[count])/100

for count in range(0,num-1)]

plt.figure(figsize=(10,6))

plt.title('Chinese GDP \'s growth rate from '+str(year_list[0])+' to '+str(year_list[-2])+'')

plt.plot(year_list[:-1],growth_rate,'r--')

plt.plot(year_list[:-1],zero,'b--')

plt.scatter(year_list[:-1],growth_rate,c='r')

plt.xlim([year_list[0], year_list[-2]])

plt.ylim([growth_rate[0]-2, max(growth_rate)+2])

plt.xlabel('Year From 1960 to 2013',fontsize = 14)

plt.ylabel('GDP growth rate ( % )',fontsize = 14)

plt.tick_params(axis='both', labelsize=14)

plt.savefig('Chinese GDP \'s growth rate from '+str(year_list[0])+' to '+str(year_list[-2])+'.png',

bbox_inches='tight')

plt.show()