4. 创建字典方式 & 默认多层嵌套字典¶
- 通过关键字dict和关键字参数创建
>>> dic = dict(spam = 1, egg = 2, bar =3)
- 通过二元组列表创建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
- dict和zip结合创建
>>> dic = dict(zip('abc', [1, 2, 3]))
- 通过字典推导式创建
>>> dic = {i:2*i for i in range(3)}
5. 通过dict.fromkeys()创建 通常用来初始化字典, 设置value的默认值, 慎用可变对象比如list,set
>>> dic = dict.fromkeys(range(3), 'x')
>>> print(dic)
{0: 'x', 1: 'x', 2: 'x'}
>>> dic = dict.fromkeys(range(3), [])
>>> dic[0].append(1)
>>> dic
{0: [1], 1: [1], 2: [1]}
>>> dic = dict.fromkeys(range(3), set())
>>> dic[0].add(1)
>>> dic
{0: {1}, 1: {1}, 2: {1}}
- 其他
>>> list = ['x', 1, 'y', 2, 'z', 3]
>>> dic = dict(zip(list[::2], list[1::2]))
>>> dic
{'y': 2, 'x': 1, 'z': 3}
7. 嵌套字典 当创建一个字典时,但却不知道字典的层级
- ::
>>> from collections import defaultdict >>> tree = lambda: defaultdict(tree) >>> root = tree() >>> root['menu']['id'] = 'file' >>> root['menu']['value'] = 'File' >>> root['menu']['menuitems']['new']['value'] = 'New' >>> root['menu']['menuitems']['new']['onclick'] = 'new();'