创建字典的几种方式(全)

1,创建空字典

dic = {}
type (dic)
#output:<type 'dict'>

2,直接赋值创建字典

dic = {'aaa':1, 'bbb':2, 'ccc':3}

3,通过dict将二元组列表创建为字典

list = [('aaa', 1), ('bbb', 2), ('ccc', 3)]
dic = dict(list)

4,通过dict和关键字参数(指的等式例如 spam = 1)创建

list = dict(aaa = 1, bbb = 2, ccc = 3)

5,将dict和zip相结合创建字典

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

关于zip函数,zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。例如:

a = [1,2,3]

b = [4,5,6]

zipped = zip(a,b)

[(1,  4), (2, 5), (3, 6)]

6,通过字典推导式创建

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

7,通过dict.fromkeys()创建,通常用来初始化字典,设置value的默认值

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