dict.fromkeys(seq[,value])
根据seq提供的key值与value值创建一个新的字典。
value值如果没有给出,默认为none。
CODE
#classmethod fromkeys() test
"""
dict.fromkeys(seq [ , value])
"""
#用seq 设置key值
seq=['name','age','sex']
"""
没有设置value,默认为None
the value is not given. value defaults to None
"""
dic_t=dict.fromkeys(seq)
print ("New Dictionary:%s"% str(dic_t))
"""
手动设置value值
"""
dic_t=dict.fromkeys(seq,'null')
print ("New Dictionary 2:%s"% str(dic_t))
"""
如果value 也是一个列表呢?
"""
value=['Bob',12,'male']
dic_t2=dict.fromkeys(seq,value)
print ("New Dictionary 3:%s"%str(dic_t2))
输出
New Dictionary:{'name': None, 'age': None, 'sex': None}
New Dictionary 2:{'name': 'null', 'age': 'null', 'sex': 'null'}
New Dictionary 3:{'name': ['Bob', 12, 'male'], 'age': ['Bob', 12, 'male'], 'sex': ['Bob', 12, 'male']}
由此可以知道,value值设定以后,对于每一个key值都是同一个value值。