Hello folks...!!!
Today let us learn how to write minimized code using dictionary comprehension.
Today let us learn how to write minimized code using dictionary comprehension.
Dictionary comprehension
The dictionary comprehension can be used for modifying an existing dictionary or create a new one with an existing iterable. Like list comprehension, the syntax is :
variable_name={expression, for loop, if-condition}
Let us look at some examples for understanding it in a better
way.
Example 1: New dictionary from existing dictionary.
Consider that there is a dictionary
containing some numbers as key and their squares as values. From this
dictionary we can create a new dictionary containing same keys and their
cubes. Look at the code snippet below:
In the above code, 'k' represents the
'keys' and 'v' represents the 'values'.
Example 2: Updating the existing dictionary.
Ram owns a shop. He has a dictionary which holds the product id's and
their prices. Now he wants increase every price by rs.5.00. Help him
update the dictionary with minimal lines of code.
Example 3: New dictionary from another iterable
Now let us create a new dictionary from a list. Consider a list of
integers. Create a dictionary, such that the items in list forms the key
and their squares form the values.
Example 4: With condition
We have a record of students in a class test. Now we have to pick up
the top scorers (marks>70) and display it starting from highest mark.
Let us look at the code :
Take a look at the line for sorting the dictionary :
sorted(toppers.items(),key=lambda v:v[1],reverse=True)
- The first parameter is the key and values from the dictionary.
- The next one is the key based on which, the dictionary is to be sorted.
- Note : The key and values are passed to lambda functions as 'v', v[0] indicates key and v[1] indicates value. Thus to sort based on the values, we use v[1].
- 'reverse=True', sorts the dictionary in descending.
Example 5: Nested for-loops
We use many abbreviations in day to day life. Most of the college names are abbreviated. One such example is, my college
name is National Institute of Technologies which is abbreviated as NIT. So
we can form a dictionary containing the abbreviations.
Example 6: Checking condition in nested loops
The example above adds words like 'of', 'and', etc,. also. But we want to
remove them. So we can include conditions. Look at the snippet below to
know how to include conditions.
Now you can notice that 'of' does not appear in the dictionary. One
more thing to note is words are not repeated in the dictionary. If the
key is already present it will be updated with the new value.
Next Topic👉
Comments
Post a Comment