Python 字典

字典可以被认为是一组无序的键-值对。

一对大括号创建一个空字典: {} 。每个元素都可以映射到某个值。整数或字符串可用于索引。字典里面的元素是没有排序的。

字典示例

让我们做一个简单的字典:

#!/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'}