默认字典,能定义默认值为其他类型
1 #dic1 = {} 2 #dic1["k1"].append("kkkkk") #正常情况会报错 3 #print(dic1) 4 5 import collections 6 dic = collections.defaultdict(list) #指定字典的值为列表 7 dic["k1"].append("kkkkk") 8 print(dic) 9 10 #执行结果: 11 defaultdict(<class 'list'>, {'k1': ['kkkkk']})
1 #有如下值集合,不用默认字典执行代码如下 2 #[11,22,33,44,55,66,77,88,99,90] 3 #将所有大于66的值保存在字典的第一个key中, 4 #将小于等于66的值保存在第二个key的值(列表)中。 5 #即:{"k1":大于66,"k2":小于等于66} 6 7 li = [11,22,33,44,55,66,77,88,99,90] 8 dic = {} 9 10 for i in li: 11 if i>66: 12 if "k1" in dic.keys(): 13 dic["k1"].append(i) 14 else: 15 dic["k1"] = [i,] 16 else: 17 if "k2" in dic.keys(): 18 dic["k2"].append(i) 19 else: 20 dic["k2"] = [i,] 21 print(dic) 22 23 #执行结果: 24 {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]}
1 #用默认字典精简代码 2 from collections import defaultdict #这样写,下面就不用写collections.defaultdict了 3 values = [11, 22, 33,44,55,66,77,88,99,90] 4 my_dict = defaultdict(list) 5 6 for value in values: 7 if value>66: 8 my_dict['k1'].append(value) 9 else: 10 my_dict['k2'].append(value) 11 print(my_dict) 12 13 #执行结果: 14 defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})