2/19/2022 conda
2/17/2022 pythonJSON
12/27/2021 Python

# 创建空字典

>>> dic = {}
>>> type(dic)
<type 'dict'>
1
2
3

# 直接赋值创建

>>> dic = {'spam':1, 'egg':2, 'bar':3}
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
1
2
3

# 通过关键字dict和关键字参数创建

>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
1
2
3

# 通过二元组列表创建

>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
1
2
3
4

# dict和zip结合创建

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

# 通过字典推导式创建

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

# 通过dict.fromkeys()创建

>>> dic = dict.fromkeys(range(3), 'x')
1
5/15/2021 pythonmap
4/6/2021 pythonmap
4/6/2021 pythonlist
3/3/2021 pythoncmd
3/3/2021 pythoncmd
2/27/2021 Python