Dictionaries are complex data structures that hold information about the different types and related information. Dictionaries also called associative memories
or associative arrays
in different languages. Dictionaries generally format in key
and value
pair. Keys are used to label and search and find values.
词典是复杂的数据结构,其中包含有关不同类型的信息和相关信息。 字典也称为不同语言的associative memories
或associative arrays
。 字典通常采用key
和value
对的格式。 键用于标记,搜索和查找值。
创建字典 (Create Dictionary)
As we say before we will provide key and value pairs. In this example, we will create a phone book. The name of the phonebook is pb
and have some names and phone numbers.
正如我们之前所说,我们将提供键和值对。 在此示例中,我们将创建电话簿。 电话簿的名称为pb
并包含一些名称和电话号码。
pb = { 'ismail':4090, 'ahmet':4091}
We have two records with keys ismail
and ahmet
their phone numbers are 4090
and 4091
. The phone numbers type is an integer. We can also define different types. We associate keys and values with :
.
我们有两个键为ismail
和ahmet
的记录,它们的电话号码分别为4090
和4091
。 电话号码类型是整数。 我们还可以定义不同的类型。 我们的键和值有关联:
。
通过钥匙获取价值 (Get Value with Key)
Getting values by providing keys. In this example, we provide the key ismail
and get the value 4090
in the following lines. As we guess the return type will be integer too.
通过提供键来获取价值。 在此示例中,我们提供键ismail
并在以下几行中获取值4090
。 我们猜想返回类型也将是整数。
ismail = pb['ismail']
向字典添加键值 (Add Key Value to Dictionary)
Adding new keys and values is as easy as getting them. We will just provide the key name and the related value by using an equal sign like below. We will add key ali
and related phone number 4092
into the phone book in the following example.
添加新键和值就像获取它们一样容易。 我们将通过使用如下所示的等号来提供密钥名称和相关值。 在以下示例中,我们将密钥ali
和相关的电话号码4092
到电话簿中。
pb['ali'] = 4092
从字典中删除键值 (Remove Key Value From Dictionary)
We can remove the given key and value by using the del
keyword. del
is a keyword in a python programming language which is used related to remove and delete operations like dictionaries, list, etc enumerable types. In the following example, we will delete the key ali
and its related value 4093
by using del
function.
我们可以使用del
关键字删除给定的键和值。 del
是python编程语言中的关键字,用于与删除和删除操作(如字典,列表等可枚举类型)相关。 在以下示例中,我们将使用del
函数删除密钥ali
及其相关值4093
。
del(pb['ali'])
使用索引作为键 (Using Index As Key)
Dictionaries provide another way for keying all ready existing key-value pairs. We can use index numbers as keys. For example, the first key value in the pb
is ismail:4090 if we provide index number 0 we can get the same value from the dictionary as below. But before we should convert dictionary values into a list.
字典提供了另一种方式来键控所有现成的现有键值对。 我们可以使用索引号作为键。 例如,如果我们提供索引号0,则pb
的第一个键值为ismail:4090,我们可以从字典中获得相同的值,如下所示。 但是在将字典值转换为列表之前。
>>> list(pb.values())[0]
4091
翻译自: https://www.poftut.com/dictionary-python-tutorial-examples/