In Python, you can use dictionary comprehensions to create a new dictionary based on an existing iterable object. This is similar to list comprehensions, but instead of creating a new list, you create a new dictionary.
Here's an example of a dictionary comprehension that creates a new dictionary based on an existing list:
# A list of numbersnumbers = [1, 2, 3, 4, 5]# A dictionary comprehension that creates a new dictionary with each number as a key and its square as the valuesquares_dict = {num: num**2 for num in numbers}# Print the dictionaryprint(squares_dict) |
In this example, we define a list of numbers called numbers, and use a dictionary comprehension to create a new dictionary called squares_dict that has each number as a key and its square as the corresponding value. The comprehension uses the syntax {key_expression: value_expression for item in iterable} to create a new key-value pair for each item in the iterable.
You can also use conditionals within dictionary comprehensions to include only certain items or modify the values based on a condition. Here's an example:
# A list of wordswords = ['apple', 'banana', 'cherry', 'durian']# A dictionary comprehension that creates a new dictionary with only the words that start with a vowel, and their lengths as valuesvowel_lengths_dict = {word: len(word) for word in words if word[0] in 'aeiou'}# Print the dictionaryprint(vowel_lengths_dict) |
In this example, we use a conditional (if word[0] in 'aeiou') within the dictionary comprehension to include only the words that start with a vowel. The value expression (len(word)) is used to assign the length of each word as the corresponding value in the dictionary.