Python创建字典的八种方式

yipeiwu_com6年前Python基础

1.创建空字典

>>> dic = {}
>>> type(dic)
<type 'dict'>

2.直接赋值创建

>>> dic = {'spam':1, 'egg':2, 'bar':3}
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

3.通过关键字dict和关键字参数创建

>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

4.通过二元组列表创建

>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

5.dict和zip结合创建

>>> dic = dict(zip('abc', [1, 2, 3]))
>>> dic
{'a': 1, 'c': 3, 'b': 2}

6.通过字典推导式创建

>>> dic = {i:2*i for i in range(3)}
>>> dic
{0: 0, 1: 2, 2: 4}

7.通过dict.fromkeys()创建

通常用来初始化字典, 设置value的默认值

>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}

8.其他

>>> list = ['x', 1, 'y', 2, 'z', 3]
>>> dic = dict(zip(list[::2], list[1::2]))
>>> dic
{'y': 2, 'x': 1, 'z': 3}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

通过实例解析python描述符原理作用

这篇文章主要介绍了通过实例解析python描述符原理作用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 本质上看,描述符是一个类,只不...

Python中时间datetime的处理与转换用法总结

python中日期类datetime功能比较强大,使用起来很方便,把常用的两种用法总结如下: from datetime import datetime from datetime...

python执行子进程实现进程间通信的方法

本文实例讲述了python执行子进程实现进程间通信的方法。分享给大家供大家参考。具体实现方法如下: a.py: import subprocess, time subproc = s...

简析Python的闭包和装饰器

简析Python的闭包和装饰器

什么是装饰器? 装饰器(Decorator)相对简单,咱们先介绍它:“装饰器的功能是将被装饰的函数当作参数传递给与装饰器对应的函数(名称相同的函数),并返回包装后的被装饰的函数”,听起来...

python里 super类的工作原理详解

super 的工作原理如下: def super(cls, inst): mro = inst.__class__.mro() return mro[mro.index(cl...