溫馨提示×

python中可以使用哪些方法創(chuàng)建字典

養(yǎng)魚的貓咪
534
2021-03-18 17:07:29
欄目: 編程語言

python創(chuàng)建字典的方法:1.通過dict關(guān)鍵字創(chuàng)建;2.通過二元組列表創(chuàng)建;3.通過字典推導(dǎo)式創(chuàng)建;4.通過dict.fromkeys()函數(shù)創(chuàng)建;

python中可以使用哪些方法創(chuàng)建字典

在python中創(chuàng)建字典的方法有以下幾種

1.通過dict關(guān)鍵字創(chuàng)建


>>> dic = dict(spam = 1, egg = 2, bar =3)

>>> dic

{'bar': 3, 'egg': 2, 'spam': 1}


2.通過二元組列表創(chuàng)建


>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]

>>> dic = dict(list)

>>> dic

{'bar': 3, 'egg': 2, 'spam': 1}


3.通過字典推導(dǎo)式創(chuàng)建


>>> dic = {i:2*i for i in range(3)}

>>> dic

{0: 0, 1: 2, 2: 4}


4.通過dict.fromkeys()函數(shù)創(chuàng)建


>>> dic = dict.fromkeys(range(3), 'x')

>>> dic

{0: 'x', 1: 'x', 2: 'x'}



0