python創建字典的方法:1.通過dict關鍵字創建;2.通過二元組列表創建;3.通過字典推導式創建;4.通過dict.fromkeys()函數創建;
在python中創建字典的方法有以下幾種
1.通過dict關鍵字創建
>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
2.通過二元組列表創建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
3.通過字典推導式創建
>>> dic = {i:2*i for i in range(3)}
>>> dic
{0: 0, 1: 2, 2: 4}
4.通過dict.fromkeys()函數創建
>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}