# 数据表记录包含表索引index和value (int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出标签:dicts,python,代码,笔试,list,value,int,key,print From: https://www.cnblogs.com/xiaocai84/p/17624554.html
# 提示 0 <= index <= 11111111 1 <= value <= 100000
times = int(input("请输入字典中键值对的个数:"))
# 定义一个字典dicts
dicts = dict()
for i in range(times):
# map(int, list)函数,可以将list中的数转成整数
# key, value = map(int, input().split())
# 将输入的字符串转成数组
key, value = input().split()
# 将key, value 转成整数,如果不转,后面的计算会是字符串拼接
key = int(key)
value = int(value)
if key >= 0 and key <= 11111111 and value >= 1 and value <= 100000:
# 如果键key在dicts.keys里面,那么相同的key对应的value值相加
if key in dicts.keys():
dicts[key] = dicts[key] + value
else:
dicts[key] = value
# dict.get(key,0)方法当key存在于字典返回key对应的value,否则返回0,这个函数可以做计数
# dicts[int(d_list[0])] = dicts.get(int(d_list[0]), 0) + int(d_list[1])
# print(dicts.get(int(d_list[0]), 0))
# print(int(d_list[1]))
else:
print("输入的key: %s超出范围(0~11111111)或者输入的value: %s超出范围(1~100000)" % (key, value))
# 将字典dicts从小到大排序,并打印出key,value
for key in sorted(dicts):
print(key, dicts[key])