对字典的索引和修改是关键,注意排序时按key值排序,最后输出的格式要注意。
num1 = int(input()) dict1 = {} for i in range(num1): index,value = [int(x) for x in input().split()] k = 0 for key in dict1: if index == key: dict1[index] += value k = 1 if k == 0: dict1[index] = value dict2 = sorted(dict1.items(), key = lambda x:x[0]) for key,value in dict2: print(key, value)