defautldict() 默认值字典
# defautldict() 默认值字典
# 创建一个字典的方法:
# 1.直接创建
# dic = {'name':'zs','age':18}
# 2.
# dic = dict([('name','zs'),('age',18)])
# 3.
# dic = {k:v for k,v in [(1,2),(3,4)]}
#
dic = collections.defaultdict(int,name='zs',age=18)
print(dic['name']) # zs
print(dic['age']) # 18
print(dic['aaa']) # 0 ---> 和int对应,且把{'aaa':0}添加进来。
print(dic) # defaultdict(<class 'int'>, {'name': 'zs', 'age': 18, 'aaa': 0})
# 自定义函数充当第一个参数:
# 要求,不能有参数
def func():
return 'hello'
dic = collections.defaultdict(func,name='zs',age=18)
print(dic['aaa']) # hello
print(dic) # defaultdict(<function func at 0x02E517C8>, {'name': 'zs', 'age': 18, 'aaa': 'hello'})