python - 字典元素的总和

标签 python dictionary

我有一本名字和年龄的字典。有些名字是相同的。我想总结相同名字的年龄。

我的假数据是这样的:

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/

相关文章:

Python 速成类(class) - 第 9 章 my_electric_car - get_range() 的问题

python - Keras 损失函数取决于批量大小

c++ - const map & 作为函数参数

python - 使用 Python 使用变量调用字典时遇到问题

python - 为什么 lambda 表达式结果对象的字典转换有问题?

iphone - Iphone SDK 中的特殊 TableView

python - 从命名管道读取连续数据

python - 使用二进制搜索返回下一个最高值

python - 创建一个由另一个字典的不同副本组成的字典

python - 如何以编程方式检测代码是在 nuitka 编译模式还是 python 解释模式下运行