首页 > 解决方案 > Sort a list from a file

问题描述

I have an excel file that contains the following entry like:

A 10
B 30
C 20
A 20
B 15

Using python scripting how can I get the desired output, like the sum of all the similar values :

A 30
B 45
C 20

标签: pythonpython-3.x

解决方案


d = dict()
for letter, number in line:
  d[letter] = number + d.get(letter, 0)

for x in sorted(d.keys()):
  print(x, d[x])

The second param in d.get gives a default value of 0 if letter is not already in the dictionary.

The sorted() func makes sure you are going in incr order wrt to keys.

We have a cumulative mapping and then print it out, short and sweet :)


推荐阅读