Python-Dictionary-fromkeys()

来源:互联网 发布:小型公司网络方案 编辑:程序博客网 时间:2024/06/05 21:20

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值。

0 0
原创粉丝点击