您的位置:首页技术文章
文章详情页

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

浏览:2日期:2022-07-09 11:33:14

第一种方式:使用{}

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 == eTrue

到此这篇关于Python之字典对象的几种创建方法的文章就介绍到这了,更多相关Python 字典对象创建内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Python 编程
相关文章: