python dict與collections.defaultdict的區別

from collections import defaultdict s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = collections.defaultdict(list) for k, v in s: d[k].append(v) >>輸出d:defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}) # Use dict and setdefault g = {} for k, v in s: g.setdefault(k, []).append(v) >>輸出g:{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]} # Use dict e = {} for k, v in s: e[k] = v >>輸出e:{'yellow': 3, 'blue': 4, 'red': 1}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章