# Python 字典

> 原文： [https://pythonspot.com/python-dictionaries/](https://pythonspot.com/python-dictionaries/)

字典可以看作是 _ 键的无序集合：值 _ 对。

一对大括号创建一个空字典： `{}` 。 每个元素都可以映射到某个值。 整数或字符串可用于索引。 字典没有命令。

## 字典范例

Let us make a simple dictionary:

```py
#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words["Hello"])
print(words["No"])

```

输出：

```py

Bonjour
Non

```

我们绝不限于价值部分中的单个单词定义。 演示：

```py
#!/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])

```

输出：

```py

Car
The Python Programming Language
This sentence is stored here.

```

## 处理字典

We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

```py
#!/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.

```

输出：

```py

{'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'}

```

[下载 Python 练习](https://pythonspot.com/download-python-exercises/)