Python字典对象的创建(9种方式)
第一种方式:使用{}
firstDict = { " name " : " wang yuan wai " , " age " : 25}
说明:{}为创建一个空的字典对象
第二种方式:使用fromkeys()方法
second_dict = dict.fromkeys(( " name " , " age " )) # value使用默认的None,也可以指定value值
说明:fromkeys()是dict类的一个staticmethod(静态方法)
第三种方式:使用dict的构造方法,参数为关键字参数
thirdDict = dict(name = " yuan wai " , age = 30) # 利用dict的构造方法 传入字典参数
第四种方式:使用dict的构造方法,参数为嵌套元组的list
tuple_list =[( " name " , " wang yuan wai " ), ( " age " , 30 )]
my_dict = dict(tuple_list)
说明:传入的list结构是有要求的,list的每个元素都是一个两个元素的tuple
第五种方式:使用dict的构造方法,参数为zip()函数的返回值
fifthDict = dict(zip( " abc " ,[1,2,3]))
第六种方式:使用dict的初始化方法,参数为字典对象
e = dict({ ' three ' : 3, ' one ' : 1, ' two ' : 2})
第七种方式:使用字典解析式
sixthDict = {char : char* 2 for char in " TEMP " }
创建字典的方式(官方文档介绍)
以下示例返回的字典均等于 {“one”: 1, “two”: 2, “three”: 3}
>>> a = dict(one=1, two=2, three=3 ) >>> b = { ' one ' : 1, ' two ' : 2, ' three ' : 3 } >>> c = dict(zip([ ' one ' , ' two ' , ' three ' ], [1, 2, 3 ])) >>> d = dict([( ' two ' , 2), ( ' one ' , 1), ( ' three ' , 3 )]) >>> e = dict({ ' three ' : 3, ' one ' : 1, ' two ' : 2 }) >>> a == b == c == d == e
True
第八种方式:使用字典的copy()方法(浅复制)创建一个新的字典对象
>>> hold_list=[1,2,3 ] >>> old_dict={ " num " :hold_list} >>> new_dict= old_dict.copy() >>> id(old_dict[ " num " ]) 2141756678856 >>> id(new_dict[ " num " ]) 2141756678856
浅复制:old_dict与new_dict持有的是同一个hold_list对象,你明白了吗?注意看id值
第九种方式:使用copy模块的deepcopy()函数(深复制)创建一个新的字典对象
>>> from copy import deepcopy >>> hold_list=[1,2 ] >>> old_dict={ " num " :hold_list} >>> new_dict= deepcopy(old_dict) >>> id(old_dict[ " num " ]) 2141787030152 >>> id(new_dict[ " num " ]) 2141787012040 # Python学习交流群 708525271
深复制:new_dict持有的也是一个新创建的host_list对象,你明白了吗?注意看id值