# dic1 = {}
# dic1["k1"].append("kkkkk") #正常情況會報錯
# print(dic1)
import collections
dic = collections.defaultdict(list) # 指定字典的值為列表
dic[ " k1 " ].append( " kkkkk " )
print (dic)
# 執行結果:
defaultdict(< class ' list ' >, { ' k1 ' : [ 'kkkkk' ]})
# 有如下值集合,不用默認字典執行代碼如下
# [11,22,33,44,55,66,77,88,99,90]
# 將所有大於66的值保存在字典的第一個key中,
# 將小於等於66的值保存在第二個key的值(列表)中。
# 即:{"k1":大於66,"k2":小於等於66}
li = [11,22,33,44,55,66,77,88,99,90 ]
dic = {}
for i in li:
if i>66 :
if " k1 " in dic.keys():
dic[ " k1 "].append(i)
else :
dic[ " k1 " ] = [i,]
else :
if " k2 " in dic.keys():
dic[ " k2 " ].append(i)
else :
dic[ " k2 " ] = [i,]
print (dic)
# 執行結果:
{ ' k2 ': [11, 22, 33, 44, 55, 66], ' k1 ' : [77, 88, 99, 90]}
# 用默認字典精簡代碼
from collections import defaultdict #這樣寫,下面就不用寫collections.defaultdict了
values = [11, 22, 33,44,55,66,77,88,99,90 ]
my_dict = defaultdict(list)
for value in values:
if value>66 :
my_dict[ ' k1 ' ].append(value)
else :
my_dict[ ' k2 ' ].append(value)
print(my_dict)
# 執行結果:
defaultdict(< class ' list ' >, { ' k2 ' : [11, 22, 33, 44, 55, 66], ' k1 ' : [77, 88, 99, 90 ]})