1. 程式人生 > >Python之字典中的鍵映射多個值

Python之字典中的鍵映射多個值

多個 pen pytho code col collect ons pan 映射

字典的鍵值是多個,那麽就可以用列表,集合等來存儲這些 鍵值

舉例

print({"key":list()})   # {‘key‘: []}
print({"key":set()})  # {‘key‘: set()}

那麽Python中有哪些方法能創建這樣的字典呢

from collections import defaultdict
dic_list=defaultdict(list)   # defaultdict(<class ‘list‘>, {})
print(dic_list)
dic_list["key"].append(1)
print
(dic_list) # defaultdict(<class ‘list‘>, {‘key‘: [1]})

Python之字典中的鍵映射多個值