2️⃣ Dictionary Comprehension
Similarly we can get required dictionary from current dictionary using dictionary comprehension.
We have seen dictionary method .items() while understanding dictionary datatype,it returns the list of tuples containing key-value pairs.
Dictionary comprehension is optimal way and requires less number of lines as compared with using forloop logic.
Scenario 1: We have dictionary which contains keys as numbers & values as strings as follow. We want a new dictionary ‘len_dict’ which should have keys as numbers but values as length of the string.
💻 Example 1:
1 2 3 4 5 6 7 8 | # implementation using for loop
string_dict = {1:'Hi', 2:'Bye', 3:'Morning', 4:'Hello'}
len_dict={}
for k in string_dict:
len_dict[k] = len(string_dict[k])
print(len_dict)
|
✅ Output:
{1:2, 2:3, 3:7, 4:5}
Lets implement it using dictionary comprehension:
💻 Example 2:
1 2 3 4 | # using dictionary comprehension
string_dict = {1:'Hi', 2:'Bye', 3:'Morning', 4:'Hello'}
len_dict = {k:len(v) for(k,v) in string_dict.items()}
print(len_dict)
|
✅ Output:
{1:2, 2:3, 3:7, 4:5}
Scenario 2: We have dictionary which represents division names as keys & no. of students as values. We want new dictionary which only contains the division keys which are having more than 100 students as values.
💻 Example 1:
1 2 3 4 5 6 7 8 | # implementation using for loop
division_count = {'divA':35, 'divB':79, 'divC':137, 'divD':150, 'divE':99, 'divF':175}
required_dict = {}
for k in division_count:
if division_count[k]>100:
required_dict[k]=division_count[k]
print(required_dict)
|
✅ Output:
{'divC':137, 'divD':150, 'divF':175}
Lets increment it using dictionary comprehension:
💻 Example 2:
1 2 3 4 5 | # implementation using dictionary comprehension
division_count = {'divA':35, 'divB':79, 'divC':137, 'divD':150, 'divE':99, 'divF':175}
required_dict = {k:v for (k,v) in division_count.items() if v>100}
print(required_dict)
|
✅ Output:
{'divC':137, 'divD':150, 'divF':175}
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What is list comprehension in Python?
How does list comprehension differ from traditional loop and appending to a list?
Can you use conditional statements in list comprehension? If yes, how?
Filter the given list [1,2,3,4,5,6] and prepare odd numbers list using list comprehension.
What is dictionary comprehension in Python?
What is difference between list and dictionary comprehension?
Can you use conditional statements in dictionary comprehension? If yes, how?