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)
#result = {'a': 1, 'b': 4}
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)
#result = {'a': 1, 'b': 4}
dictionary comprehension python
square_dict = {num: num*num for num in range(1, 11)}
dict comprehension python
# 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}
python dictionary comprehension
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
types of dict comprehension
# Dictionary Comprehension Types
{j:j*2 for i in range(10)}
#using if
{j:j*2 for j in range(10) if j%2==0}
#using if and
{j:j*2 for j in range(10) if j%2==0 and j%3==0}
#using if else
{j:(j*2 if j%2==0 and j%3==0 else 'invalid' )for j in range(10) }
dictionary comprehension in python
# dictionary comprehension
# these are a little bit tougher ones than list comprehension
sample_dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
# making squares of the numbers using dict comprehension
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)
# if you don't have a dictionary and you wanna create a dictionary of a number:number**2
square_without_dict = {num:num**2 for num in range(11)}
print(square_without_dict)
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us