假设你有一个键-值对序列:
>>> datas=[('100',3), ('161',4), ('200',7), ('100', 5), ('200',11)]
需要将它以键为主体求和转换成下面这种字典:
{'100': 8, '161': 4, '200': 18}
你会怎么处理?
当然,常用的处理方法自然也可以达到同样的目的,像下面这种:
>>> datas=[('100',3), ('161',4), ('200',7), ('100', 5), ('200',11)]
>>> total_count = {}
>>> for data in datas:
if data[0] not in total_count:
total_count[data[0]] = data[1]
else:
total_count[data[0]] += data[1]
>>> total_count
{'100': 8, '161': 4, '200': 18}
但是这种需要你自己添加判断,判断字典里边是否有对应的键,没有的话得自己设定键的值。
如果使用defaultdict的话,自然就简单多了:
>>> datas=[('100',3), ('161',4), ('200',7), ('100', 5), ('200',11)]
>>> from collections import defaultdict
>>> total_count = defaultdict(int)
>>> for data in datas:
total_count[data[0]] += data[1]
>>> total_count
defaultdict(<class 'int'>, {'100': 8, '161': 4, '200': 18})