English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Compréhension de dictionnaire en Python

Dans ce tutoriel, nous allons apprendre la compréhension de dictionnaire en Python et comment l'utiliser avec l'aide d'exemples.

Le dictionnaire est un type de données en Python qui nous permet de stocker des données dansClé/Paires de valeursPar exemple :

my_dict = {1: 'apple', 2: 'ball'

Pour en savoir plus à leur sujet, veuillez visiter :Dictionnaire Python

Qu'est-ce que la compréhension de dictionnaire en Python ?

La compréhension de dictionnaire est une méthode élégante et concise pour créer un dictionnaire.

Example1: Compréhension de dictionnaire

Considérons le code suivant :

square_dict = dict()
for num in range(1, 11) :
    square_dict[num] = num*num
print(square_dict)

Maintenant, utilisons la fonction de compréhension de dictionnaire pour créer un dictionnaire dans le programme ci-dessus.

# Exemple de compréhension de dictionnaire
square_dict = {num: num*num pour num dans range(1, 11)}
print(square_dict)

Les sorties des deux programmes seront identiques.

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Dans ces deux programmes, nous avons tous créés square_dict avec数字平方键/值对的字典。

但是,使用字典理解可以使我们在一行中创建字典

使用字典理解

从上面的示例中,我们可以看到字典理解应该以特定的模式编写。

字典理解的最小语法为:

dictionary = {key: value for vars in iterable}

让我们将此语法与上例中的字典理解进行比较。

现在,让我们看看如何使用另一个字典中的数据来使用字典理解。

Example3:如何使用字典理解

#item price in dollars
old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
dollar_to_pound = 0.76
new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()}
print(new_price)

Output results

{'milk': 0.7752, 'coffee': 1.9, 'bread': 1.9}

在这里,我们可以看到我们以美元为单位检索商品价格并将其转换为英镑。使用字典理解使此任务更加简单和短。

字典理解中的条件

我们可以通过添加条件来进一步自定义字典理解。让我们来看一个实例。

Example4:如果条件字典理解

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0}
print(even_dict)

Output results

{'jack': 38, 'michael': 48}

我们可以看到,由于if字典理解中的子句,仅添加了具有偶数值的项目。

Example5:多重if条件字典理解

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
new_dict = {k: v for (k, v) in original_dict.items() if v % 2 != 0 if v < 40}
print(new_dict)

Output results

{'john': 33}

在这种情况下,仅奇数值小于40的项目已添加到新字典中。

这是因为if字典理解中有多个子句。它们等效于and必须同时满足两个条件的操作。

Example6:if-else条件字典理解

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
new_dict_1 = {k: ('old' if v > 40 else 'young'
    for (k, v) in original_dict.items()}
print(new_dict_1)

Output results

{'jack': 'young', 'michael': 'old', 'guido': 'old', 'john': 'young'}

In this case, a new dictionary will be created through sub-dictionary comprehension.

greater than or equal to4The value of the product of 0 is 'old', and the value of other products is 'young'.

Nested dictionary comprehension

We can add dictionary comprehension itself to dictionary comprehension to create nested dictionaries. Let's look at an example.

Example7: nested dictionary with two dictionary comprehensions

dictionary = {
    k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5)
}
print(dictionary)

Output results

{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}}

As you can see, we have constructed a multiplication table in the nested dictionary for2to4of numbers.

Every time you use nested dictionary comprehension, Python will start from the outer loop first, and then enter the inner loop.

Therefore, the above code is equivalent to:

dictionary = dict()
for k1 in range(11, 16) :
    dictionary[k1] = {k2: k1*k2 for k2 in range(1, 6)}
print(dictionary)

It can be expanded further:

dictionary = dict()
for k1 in range(11, 16) :
    dictionary[k1] = dict()
    for k2 in range(1, 6) :
        dictionary[k1][k2] = k1*k2
print(dictionary)

These three programs all give us the same output.

Advantages of using dictionary comprehensions

As we have seen, dictionary comprehensions greatly shorten the process of dictionary initialization. It makes the code more pythonic.

Using dictionary comprehensions in our code can shorten the lines of code while maintaining logical integrity.

Points to consider when using dictionary comprehensions

Although dictionary comprehensions are very useful for writing easy-to-read elegant code, they are not always the correct choice.

Use them as:

  • They may sometimes slow down the execution speed of the code and consume more memory.

  • They will also reduce the readability of the code.

We must never try to add difficult logic or a large number of dictionary comprehensions just to make the code single-line. In these cases, it is best to choose other methods, such as loops.