假設你有一個鍵-值對序列:
>>> 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})