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}
L1=list(“abcdef”)
L1
['a', 'b', 'c', 'd', 'e', 'f']
T=list(enumerate(l1,start=1))
T
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]
Dict(t)
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
Dict(zip(“abcd”,range(4)))
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
dict(list(enumerate(list("abcdef"),start=1)))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}