创建一个空字典
empty_dict = dict() print(empty_dict) {}
用
**kwargs
可变参数传入关键字创建字典a = dict(one=1,two=2,three=3) print(a) {'one': 1, 'two': 2, 'three': 3}
传入可迭代对象
b = dict(zip(['one','two','three'],[1,2,3])) print(b) {'one': 1, 'two': 2, 'three': 3}
```python
dic = dict(zip('abc', [1, 2, 3]))
print(dic)
{'a': 1, 'c': 3, 'b': 2}
```
**如果传入的两个列表长度不同,则截取最短的那个创建字典**
```python
b = dict(zip(['one', 'two', 'three'],[1, 2, 3, 4]))
#或者
b = dict(zip(['one', 'two', 'three', 'four'],[1,2,3]))
print(b)
{'one': 1, 'two': 2, 'three': 3}
```
通过二元组列表创建
如果有不是二元数组的项会报错
c = dict([('one', 1), ('two', 2), ('three', 3)]) print(c) {'one': 1, 'two': 2, 'three': 3} #如果键有重复,其值为最后重复项的值。 c1 = dict([('one', 1), ('two', 2), ('three', 3),('three', 4),('three', 5)]) print(c1) {'one': 1, 'two': 2, 'three': 5}
传入映射对象,字典创建字典
d = dict({'one': 1, 'two': 2, 'three': 3}) print(d) {'one': 1, 'two': 2, 'three': 3}
通过字典推导式创建
dic = {i:2*i for i in range(3)} print(dic) {0: 0, 1: 2, 2: 4}
通过dict.fromkeys()创建
通常用来初始化字典, 设置value的默认值dic = dict.fromkeys(range(3), 'x') print(dic) {0: 'x', 1: 'x', 2: 'x'}