Python创建字典多种方式
Posted target2018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python创建字典多种方式相关的知识,希望对你有一定的参考价值。
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创建字典多种方式的主要内容,如果未能解决你的问题,请参考以下文章