1simple_dict = {
2 'a': 1,
3 'b': 2
4}
5my_dict = {key: value**2 for key,value in simple_dict.items()}
6print(my_dict)
7#result = {'a': 1, 'b': 4}
1# dict comprehension we use same logic, with a difference of key:value pair
2# {key:value for i in list}
3
4fruits = ["apple", "banana", "cherry"]
5print({f: len(f) for f in fruits})
6
7#output
8{'apple': 5, 'banana': 6, 'cherry': 6}
1dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
2# Double each value in the dictionary
3double_dict1 = {k:v*2 for (k,v) in dict1.items()}
4# double_dict1 = {'e': 10, 'a': 2, 'c': 6, 'b': 4, 'd': 8} <-- new dict
1# dictionary comprehension
2# these are a little bit tougher ones than list comprehension
3
4sample_dict = {
5 'a': 1,
6 'b': 2,
7 'c': 3,
8 'd': 4,
9 'e': 5
10}
11
12# making squares of the numbers using dict comprehension
13square_dict = {key:value**2 for key, value in sample_dict.items()}
14print(square_dict)
15
16square_dict_even = {key:value**2 for key, value in sample_dict.items() if value % 2 == 0}
17print(square_dict_even)
18
19# if you don't have a dictionary and you wanna create a dictionary of a number:number**2
20square_without_dict = {num:num**2 for num in range(11)}
21print(square_without_dict)
22
23
1names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
2heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
3
4my_dict= {name: hero for name, hero in zip(name,hero)}
5