Python之字典对象的几种创建方法

第一种方式:使用{}

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)]

说明:传入的list结构是有要求的,list的每个元素都是一个两个元素的tuple

第五种方式:使用dict的构造方法,参数为zip()函数的返回值

fifthDict = dict(zip("abc",[1,2,3]))

第六种方式:使用字典解析式

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