Python Comprehension#

  • This blog contains how to create dictionary, list, tuples etc through using comprehension and solve problems faster

Dictionary Comprehension#

[1]:
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
dict_1={key:value for (key,value) in zip(state,capital)}
print(dict_1)
{'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}

Sample Question#

Make a program, which generates a dictionary variable a = {“January”:1, “February”:2, “May”:5} and prints keys of a sorted by value of the dictionary in descending order. In this time, use “for” function.And then use comprehension to solve it.

May
February
January
#### Method1 Using For
[4]:
a  = {"January":1, "February":2, "May":5}
sorted_value=sorted(a.values(), reverse=True)
print(sorted_value)
for val in sorted_value:
    print([x for x in a.items() if x[1] == val][0][0])
[5, 2, 1]
May
February
January

Method2 Using Comprehension#

[8]:
sorted_value=sorted(a.items(),key=lambda x:x[1],reverse=True)
[print(var[0]) for var in sorted_value]
May
February
January
[8]:
[None, None, None]