位置:首頁 » Python3入門教學 » Python3 字典

Python3 字典 [編輯]

字典可以被看作是一個無序的鍵 : 值對。 一對大括號用於創建一個空的字典: {}.  每個元素可以映射到一個特定的值。整數或字符串可以用來作索引。字典冇有順序。讓我們用一個例子作一個簡單的解釋:

#!/usr/bin/python
 
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"
 
print words["Hello"]
print words["No"]

輸出:

Bonjour
Non

我們並不局限於在值部分來用單詞的定義。一個演示:

#!/usr/bin/python
 
dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."
 
print dict['Ford']
print dict['Python']
print dict[2]

輸出:

Car
The Python Programming Language
This sentence is stored here.

操作字典
我們可以在字典聲明之後操作存儲在其中的數據。這顯示在下麵的例子:

#!/usr/bin/python
 
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"
 
print words            # print key-pairs.
del words["Yes"]       # delete a key-pair.
print words            # print key-pairs.
words["Yes"] = "Oui!"  # add new key-pair.
print words            # print key-pairs.

輸出:

{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}