pcwu's TIL Notes


[Python] Dict 的 setdefault 和 defaultdict

Python 在將一堆資料新增到 dict 裡時,常常會面臨第一次加入時,要檢查是否存在某 key

the_dict = {}
for author, book in books:
    if author not in the_dict:
        the_dict[author] = []
    the_dict[author].append(book)

其實 Python 有內建一個 setdefault 來解決這個問題,可以大大簡化程式:

the_dict = {}
for author, book in books:
    the_dict.setdefault(author, []).append(book)

但如果整個 dict 的預設值都相同的話(像是都是空白的 list),其實可以更進一步使用 defaultdict

import collections

the_dict = collections.defaultdict(list)
for author, book in books:
    the_dict[author].append(book)

Reference