Dictionary Comprehension Python


In Python, a dictionary is a list of elements that can only be retrieved using a unique key instead of indexing. Similar to a list in Python, the items can be stored in dictionaries. But instead of utilizing the item’s index to retrieve it, we provide the item in the dictionary with a unique key and then utilize it to do so. A technique for converting one dictionary into the other is called ”dictionary comprehension.”

Elements from the initial dictionary could be explicitly added to the new one throughout this conversion, and every element will undergo the appropriate modifications. The program may become more descriptive and hence simpler to comprehend if it has dictionary comprehension. Being able to obtain a dictionary’s key elements and the value of those elements is necessary for dictionary comprehension. The ‘for’ loop and lambda methods will be replaced with the use of dictionary comprehension. In this article, we will talk about dictionary comprehension in detail.

Example no 1:

In this scenario, we are going to use a ‘for’ loop with dictionary comprehension.

num = range(20)
new_dict = {}

for i in num:
    if i%2==0:
        new_dict[i] = i**3

print(new_dict)

First, we declare a variable ‘num’ and along with this, we define the range of the numbers. Another variable, ‘new_dict’ is being initialized, and this list will be set as an empty list. Now we are going to add different values to the dictionary ‘new_dict’ by the use of the ‘for’ loop. We initialize a loop variable ‘i’. We apply the condition on the loop variable that the defined value will be completely divided by 2. And then we apply multiplication to the values of the dictionary. The values will be multiplied by 3. In the last, we apply the print() function to display the elements.

Example no 2:

The alternate method used in place of ‘for’ loops is the deployment of dictionary comprehension. For loops have been applied in computer programs to continuously run a specific function or a series of commands for a defined couple of iterations. Nested for loops, where one for loop is present inside the other, become complicated and perplexing. In these situations, dictionary comprehension is preferable since it makes the program easier to read and comprehend properly.

num = range(20)
new_dict = {}
new_dict = {i:i**2 for i in num if i%2 == 0}

print(new_dict)

The range of the numbers is specified concurrently with the initial declaration of the variable “num.” This list would be configured as an empty list as another variable, ‘new_dict’, is initialized. We will use the for loop within the variable “new_dict” because we will be adding various values to the dictionary. We set the value of the loop variable “i.” On the dictionary’s values, multiplication is being used. The numbers will receive a 2x multiplier. On the loop variable, we provide a condition that the defined value will be evenly divided by 2. The print() function is finally invoked to print the values of the dictionary.

Example no 3:

The lambda method can also be approached using dictionary comprehension. The dictionary comprehension technique is an alternative technique for the lambda method. Some unidentified operations can be created by utilizing lambda methods. These include nameless procedures. These are reusable methods that are only used in the context in which they were assembled. Some functionalities are frequently combined with the lambda method.

fahrenheit = {‘t1’:-40, ‘t2’:-50, ‘t3’:-60, ‘t4’:10}
celsius = list(map(lambda a: (float(5)/9)*(a-32), fahrenheit.values()))
celsius_dict = dict(zip(fahrenheit.keys(), celsius))
print(celsius_dict)

We will initialize the Fahrenheit dictionary and define four temperatures. This dictionary is stored in the ‘fahrenheit’. We use the Celsius formula to convert the Fahrenheit temperature into a Celsius temperature. For this purpose, we utilize the lambda() function. By using this, we can obtain the appropriate Celsius values. We declare a variable ‘celsius_dict’ to create the Celsius dictionary.

Here we also utilize the zip() function. The inbuilt zip() method in Python iterates through the values and accumulates them. Fahrenheit.keys() and Celsius are two parameters of the zip() method. This instance utilizes the zip method to combine the elements of fahrenheit.keys() and the celsius dictionary, creating the appropriate key-value combination, which will be combined with other items in a dictionary by the use of the dict() method. Lastly, we will show the dictionary of Celsius by calling the print() function.

By using the dictionary comprehension, the outcome is clear and simple to comprehend. Thus, dictionary comprehension will be a useful replacement for lambda methods.

Example no 4:

Nested dictionary comprehension will be used in this instance. Information that is assembled in levels and wherever items incorporate additional things that are identical to them is called nesting in development. We would have frequently observed nested “if” statements that are composed of one if expression within the other one. Likewise, comprehensions and dictionaries could also be nested.

nested_dict = {‘third’:{‘x’:8}, ‘fourth’:{‘z’:9}}
float_dict = {outer_l: {float(inner_b) for (inner_l, inner_b) in outer_b.items()} for (outer_l, outer_b) in nested_dict.items()}
print(float_dict)

We create a dictionary that contains two values. In the next step, we will declare another dictionary that has some floating-point values. Within this dictionary, we configure a nested dictionary. This dictionary is stored in a variable ‘float_dict’. Then the print() function is employed to print the floating dictionary.

In this case, the variable “nested_dict” would be a dictionary having the values third and fourth storing dictionary elements as the data. The internal dictionary contents are used by the program, and when they have been transformed into floating-point values, the outer values and the initial floating-point numbers are merged to create a unique dictionary.

Conclusion:

This guide introduces us to dictionaries first, then illustrates what comprehension is and why it’s important, as well as certain situations in which it can be helpful, particularly when using dictionaries. We also successfully employ dictionary comprehension in a variety of programs that we run. A dictionary comprehension in Python loops through the values in a dictionary, enabling users to modify or analyze every element to develop a different dictionary. In this article, we also discussed how to utilize dictionary comprehension in place of the ‘for’ loop and lambda methods.



Source link