标签:列表 rom 初始 字典推导式 div col 创建 赋值 code
1 >>> dic = {} 2 >>> type(dic) 3 <type ‘dict‘>
1 >>> dic = {‘spam‘:1, ‘egg‘:2, ‘bar‘:3} 2 >>> dic 3 {‘bar‘: 3, ‘egg‘: 2, ‘spam‘: 1}
1 >>> dic = dict(spam = 1, egg = 2, bar =3) 2 >>> dic 3 {‘bar‘: 3, ‘egg‘: 2, ‘spam‘: 1}
1 >>> list = [(‘spam‘, 1), (‘egg‘, 2), (‘bar‘, 3)] 2 >>> dic = dict(list) 3 >>> dic 4 {‘bar‘: 3, ‘egg‘: 2, ‘spam‘: 1}
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}
通常用来初始化字典, 设置value的默认值
1 >>> dic = dict.fromkeys(range(3), ‘x‘) 2 >>> dic 3 {0: ‘x‘, 1: ‘x‘, 2: ‘x‘}
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}
标签:列表 rom 初始 字典推导式 div col 创建 赋值 code
原文地址:https://www.cnblogs.com/target2018/p/9886716.html