字典可以被看作是一个无序的键 : 值对。 一对大括号用于创建一个空的字典: {}. 每个元素可以映射到一个特定的值。整数或字符串可以用来作索引。字典没有顺序。让我们用一个例子作一个简单的解释:
#!/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'}