我有一本名字和年龄的字典。有些名字是相同的。我想总结相同名字的年龄。
我的假数据是这样的:
pete: 33
ann: 7
ruth: 3
ann: 5
austin: 90
示例中有两个ann。所以我想把两个安的年龄相加。 目前我有一本字典:
dict = {'pete':33,'ann':7,'ruth':3,'ann':5,'austin':90}
我的结果应该是这样的
dict = {'pete':33,'ann':12,'ruth':3,'austin':90}
pete: 33
ann: 12
ruth: 3
austin: 90
我认为像这样将数据放入字典中并不是最佳解决方案。存储数据并将其处理成输出的其他好的解决方案是什么?
最佳答案
你的假数据不能看起来像那样。字典中不可能有两个具有相同键的条目,也许您打算使用不同的数据结构? (不是字典)。但是如果你的数据是这样的:
input = [('pete', 33), ('ann',7), ('ruth',3), ('ann',5), ('austin',90)]
那么 defaultdict
会是个好主意:
from collections import defaultdict
d = defaultdict(int)
for k, v in input:
d[k] += v
d
=> defaultdict(<type 'int'>, {'pete': 33, 'ann': 12, 'ruth': 3, 'austin': 90})
或者使用计数器
:
from collections import Counter
d = Counter()
for k, v in input:
d.update({k:v})
d
=> Counter({'austin': 90, 'pete': 33, 'ann': 12, 'ruth': 3})
还有另一种解决方案,无需导入额外的库:
d = {}
for k, v in input:
if k in d:
d[k] += v
else:
d[k] = v
d
=> {'pete': 33, 'ann': 12, 'ruth': 3, 'austin': 90}
关于python - 字典元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17958818/