xxxxxxxxxx
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
# double_dict1 = {'e': 10, 'a': 2, 'c': 6, 'b': 4, 'd': 8} <-- new dict
xxxxxxxxxx
simple_dict = {
'a': 1,
'b': 2
}
my_dict = {key: value**2 for key,value in simple_dict.items()}
print(my_dict)
#result = {'a': 1, 'b': 4}
xxxxxxxxxx
users = {'sam': 20, 'mike': 30, 'joe': 40}
# return users where the ave is greater than 20
users_over_20 = {k: v for k, v in users.items() if v > 20}
# print users over 20
print(users_over_20)
# output {'mike': 30, 'joe': 40}
xxxxxxxxxx
# dict comprehension we use same logic, with a difference of key:value pair
# {key:value for i in list}
fruits = ["apple", "banana", "cherry"]
print({f: len(f) for f in fruits})
#output
{'apple': 5, 'banana': 6, 'cherry': 6}
xxxxxxxxxx
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)