Python 中的字典資料型別


Python 的字典屬於雜湊表型別。它們像 Perl 中的關聯陣列或雜湊表一樣運作,並由鍵值對組成。字典鍵可以是幾乎任何 Python 型別,但通常是數字或字串。而值可以是任何任意的 Python 物件。

示例

字典用大括號 ({ }) 括起來,可以使用方括號 ([]) 分配和訪問值。例如 −

 演示

#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

輸出

產生以下結果 −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

字典元素之間沒有順序概念。錯誤地認為元素“無章可循”,它們只是無序的。

更新於: 24-1 月-2020

13K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告