8
Lesson 8
Combining list comprehensions with Dictionaries or Sets
In Python, list comprehensions are a very convenient way to create new lists by transforming or filtering elements from existing ones. But did you know that you can also use list comprehensions with dictionaries and sets? This allows you to easily create dictionaries or sets based on conditions or transformations, just like you would with lists.
A dictionary in Python stores key-value pairs. When using a list comprehension with dictionaries, you can create a new dictionary by iterating over some collection (like a list) and applying conditions or transformations to the keys and/or values.
Basic Example: Create a Dictionary from a list
Let’s say you have a list of words, and you want to create a dictionary where the key is the word, and the value is the length of that word.
List comprehension with Dictionaries
A dictionary in Python stores key-value pairs. When using a list comprehension with dictionaries, you can create a new dictionary by iterating over some collection (like a list) and applying conditions or transformations to the keys and/or values.
Basic Example: Create a Dictionary from a list
Let’s say you have a list of words, and you want to create a dictionary where the key is the word, and the value is the length of that word.
words = ["apple", "banana", "cherry"] word_lengths = {word: len(word) for word in words} print(word_lengths) # Output: {'apple': 5, 'banana': 6, 'cherry': 6}
For each
- The
word is the key. len(word) gives the length of the word and is the value.
This results in a dictionary where each word is mapped to its length.
Example: Filter Dictionary by length
Let’s say you want to create a dictionary only for words with more than 5 characters.
words = ["apple", "banana", "cherry", "fig"] long_words = {word: len(word) for word in words if len(word) > 5} print(long_words) # Output: {'banana': 6, 'cherry': 6}
We added an
List comprehension with Sets
A set in Python is an unordered collection of unique elements. List comprehensions can be used to create sets in much the same way you use them for lists.
Basic Example: Create a Set from a List
Let's say you have a list of numbers and you want to create a set of squares of those numbers.
numbers = [1, 2, 3, 4, 5] squares = {num**2 for num in numbers} print(squares) # Output: {1, 4, 9, 16, 25}
- For each number in the list, the square (
num**2 ) is calculated and added to the set. - Since sets don’t allow duplicates, if any squared number repeats, it will appear only once in the set.
Example: Filter Set by even numbers
You can also add conditions to include only even numbers in your set.
numbers = [1, 2, 3, 4, 5] even_squares = {num**2 for num in numbers if num % 2 == 0} print(even_squares) # Output: {4, 16}
- The condition
if num % 2 == 0 filters the list to include only even numbers. - For each even number, we add its square to the set.
Combining list comprehensions with Dictionaries and Sets in practice
Here are a few practical examples to see how these concepts come together:
Example: Create a Dictionary with Set values
Let’s say you want to create a dictionary where each key is a word, and its value is a set of the unique vowels in that word.
words = ["apple", "banana", "cherry"] vowels = {'a', 'e', 'i', 'o', 'u'} word_vowels = {word: {letter for letter in word if letter in vowels} for word in words} print(word_vowels)
Output:
{'apple': {'a', 'e'}, 'banana': {'a', 'e'}, 'cherry': {'e'}}
- For each word in
words , we create a set of letters that are vowels (letter in vowels ). - This results in a dictionary where the key is the word, and the value is the set of vowels in that word.
Example: Create a Set of Keys from a Dictionary
Now, let’s say you have a dictionary of people and their ages, and you want to create a set of people who are older than 18.
ages = {"Alice": 30, "Bob": 17, "Charlie": 25, "David": 15} adults = {name for name, age in ages.items() if age > 18} print(adults) # Output: {'Alice', 'Charlie'}
- We use
.items() to loop through both keys (names) and values (ages). - The condition
if age > 18 filters the dictionary to include only adults.
Why Use List Comprehensions with Dictionaries or Sets?
1. Concise code: List comprehensions allow you to combine loops and conditionals in one line, making your code shorter and cleaner.
2. Efficiency: Using a list comprehension is often faster than using traditional loops, especially for larger datasets.
3. Readability: List comprehensions make it clear that you’re building a new dictionary or set, and the logic is more apparent than with multiple loops or if-statements.