Arjun Hooda
Arjun Hooda

Reputation: 19

Dictionary comprehensions

Dictionary comprehensions

num_dict={1:1,2:4,3:9}
twice_num_dict={key: (value if value*2 >=8 else None)for (key,value) in num_dict.items()}
print(twice_num_dict)

Dictionary comprehensionsi wanted to create a new dict where only key:value pairs of the existing dict will be there in the new_dict if the value*2 of the first dict was >=8 i used if and else here but idk what to type in else condition so that the key value pair of 1:1 is not printed at all

Upvotes: 0

Views: 68

Answers (1)

Carson
Carson

Reputation: 3101

You should place your if clause after your for clause in the comprehension, like so:

{k: v for k, v in d.items() if v * 2 >= 8}

Upvotes: 2

Related Questions