python dictionary comprehension code example
Example 1: create dictionary comprehension python
{key:value for key in iterable}
Example 2: python set and dictionary comprehensions
simple_dict = {
'a': 1,
'b': 2
}
my_dict = {key: value**2 for key,value in simple_dict.items()}
print(my_dict)
Example 3: dictionary comprehension python
square_dict = {num: num*num for num in range(1, 11)}
Example 4: python dictionary comprehension
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
Example 5: dict comprehension python
fruits = ["apple", "banana", "cherry"]
print({f: len(f) for f in fruits})
{'apple': 5, 'banana': 6, 'cherry': 6}
Example 6: dictionary comprehension in python
sample_dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
square_dict = {key:value**2 for key, value in sample_dict.items()}
print(square_dict)
square_dict_even = {key:value**2 for key, value in sample_dict.items() if value % 2 == 0}
print(square_dict_even)
square_without_dict = {num:num**2 for num in range(11)}
print(square_without_dict)