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

Tutorial Básica de Python

Control de Flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de Archivos de Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

Comprensión de diccionarios en Python

En este tutorial, aprenderemos sobre la comprensión de diccionarios en Python y cómo usarla con la ayuda de ejemplos.

El diccionario es un tipo de datos en Python que nos permite almacenar datos enClave/En el par de valores. Por ejemplo:

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

Para obtener más información sobre ellos, visite:Diccionario de Python

¿Qué es la comprensión de diccionario en Python?

La comprensión de diccionario es una manera elegante y concisa de crear diccionarios.

Example1: Comprensión de diccionario

Consideremos el siguiente código:

square_dict = dict()
por num en range(1, 11) :
    square_dict[num] = num*num
print(square_dict)

Ahora, utilicemos la función de comprensión de diccionario para crear un diccionario en el programa anterior.

# Ejemplo de comprensión de diccionario
square_dict = {num: num*num por num en range(1, 11)}
print(square_dict)

La salida de los dos programas será la misma.

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

En estos dos programas, hemos creado square_dict con数字平方键/值对的字典。

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

使用字典理解

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

字典理解的最小语法为:

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.

Value 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.

When using nested dictionary comprehensions, Python will first start from the outer loop 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 give us the same output.

Advantages of using dictionary comprehensions

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

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

Points to note 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 code execution speed and occupy 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 alternative methods, such as loops.