5 Practical Examples of Dict Comprehension with If-Else Statements
Have you ever found yourself creating a dictionary using for loops that extend over multiple lines, trying to account for the various if-else conditions that affect the values of your dictionary’s keys and values? Well, you’re not alone! Dictionary comprehension with if-else statements can save you time and help you write cleaner, more readable code. In this article, we’ll explore five practical examples of dictionary comprehension with if-else statements.
Example 1: Mapping Word Length
Suppose you have a list of words and want to create a dictionary that contains each word and its corresponding length. You can use dictionary comprehension with if-else statements to map the word length to each word.
“`
words = [‘apple’, ‘banana’, ‘pear’, ‘grape’, ‘lemon’]
word_length = {word: len(word) for word in words if len(word) > 4}
print(word_length)
“`
In this example, we’re filtering out words that are less than or equal to four characters long. The output will be:
“`
{‘banana’: 6, ‘grape’: 5, ‘lemon’: 5}
“`
Example 2: Mapping Word Frequency
Suppose you have a list of words and want to create a dictionary that contains each word and its frequency. You can use dictionary comprehension with if-else statements to count the frequency of each word.
“`
words = [‘apple’, ‘banana’, ‘pear’, ‘grape’, ‘lemon’, ‘banana’]
word_frequency = {word: words.count(word) for word in words if words.count(word) > 1}
print(word_frequency)
“`
In this example, we’re filtering out words that appear only once in the list. The output will be:
“`
{‘banana’: 2}
“`
Example 3: Filtering Dictionary Elements
Suppose you have a dictionary that contains student names and scores, and you want to filter out students who scored below a certain threshold. You can use dictionary comprehension with if-else statements to filter out dictionary elements.
“`
scores = {‘Alice’: 85, ‘Bob’: 70, ‘Charlie’: 60, ‘David’: 90, ‘Eva’: 55}
passing_scores = {name: score for name, score in scores.items() if score >= 70}
print(passing_scores)
“`
In this example, we’re filtering out students who scored below 70. The output will be:
“`
{‘Alice’: 85, ‘Bob’: 70, ‘David’: 90}
“`
Example 4: Creating Nested Dictionaries
Suppose you have a list of courses and their corresponding grades for each student, and you want to create a nested dictionary that contains each student and their corresponding courses and grades. You can use nested dictionary comprehension with if-else statements to create the nested dictionary.
“`
students = {‘Alice’: [(‘Math’, 85), (‘Science’, 70), (‘History’, 90)],
‘Bob’: [(‘Math’, 70), (‘Science’, 75), (‘History’, 60)],
‘Charlie’: [(‘Math’, 60), (‘Science’, 80), (‘History’, 85)]}
student_courses = {name: {course: grade for course, grade in courses if grade >= 70} for name, courses in students.items()}
print(student_courses)
“`
In this example, we’re only including courses in the nested dictionary if the grade is greater than or equal to 70. The output will be:
“`
{‘Alice’: {‘Math’: 85, ‘History’: 90},
‘Bob’: {‘Math’: 70, ‘Science’: 75},
‘Charlie’: {‘Science’: 80, ‘History’: 85}}
“`
Example 5: Creating a Switch Statement
Suppose you have a variable that can take on one of several values, and for each value, you want to execute a different set of statements. You can use dictionary comprehension with if-else statements to create a switch statement.
“`
variable = ‘B’
case_statements = {‘A’: ‘Execute case A statements’,
‘B’: ‘Execute case B statements’,
‘C’: ‘Execute case C statements’}
exec(case_statements.get(variable, ‘Invalid case statement’))
“`
In this example, we’re using the get method to retrieve the case statement that corresponds to the value of the variable. If the variable is not in the dictionary, we’re printing an ‘Invalid case statement’ message.
In conclusion, using dictionary comprehension with if-else statements can make your code more concise and readable. By applying the five practical examples we’ve explored, you can save time while writing cleaner code.
(Note: Do you have knowledge or insights to share? Unlock new opportunities and expand your reach by joining our authors team. Click Registration to join us and share your expertise with our readers.)
Speech tips:
Please note that any statements involving politics will not be approved.