首页 > 编程语言 > 详细

Python创建字典多种方式

时间:2018-11-01 10:24:33      阅读:119      评论:0      收藏:0      [点我收藏+]

1.创建空字典

1 >>> dic = {}
2 >>> type(dic)
3 <type dict>

2.直接赋值创建

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

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

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

4.通过二元组列表创建

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

5.dict和zip结合创建

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

6.通过字典推导式创建

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

7.通过dict.fromkeys()创建

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

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

8.其他

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

Python创建字典多种方式

原文:https://www.cnblogs.com/target2018/p/9886716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!