Today’s Agenda
Programs on dictionary contd…
Dictionary comprehension
Programs on dictionary contd…
Example 1: Write a program that splits the sentence and arrange
them into descending order based on their length and then in
chronological order.
lst 0 1 2 3 4 5 6
1000 jack and jill went up the hill
1000
1 Python fundamentals| Rooman Technologies
d Key Value
0 1 2 3
4
jack jill went hill
0 1
3
and the
0
2
up
Output:
2 Python fundamentals| Rooman Technologies
Dictionary comprehension
Similar to list comprehension and set comprehension, dictionary
comprehension is a concise way of creating dictionaries.
Let us start with an example where we take input from user and
want to store it as key and the value should be the length of the
word.
lst 0 1 2 3
1000 ‘India’ ‘Germany’ ‘Poland’ ‘USA’
1000
d Key Value
‘India’ 5
‘Germany’ 7
‘Poland’ 6
‘USA’ 3
Output:
3 Python fundamentals| Rooman Technologies
Output:
Example 2: From the given list of numbers take even numbers as the
key and square of it as values.
Output:
4 Python fundamentals| Rooman Technologies
Output:
Now in the same example along with the even numbers for odd
numbers let us print their cube.
Output:
Output:
5 Python fundamentals| Rooman Technologies
Example 3: To the given list check if the length is less than 6 if so
convert it into uppercase and cube the value of length and if the
length is greater than or equal to 6 then just square the length
value.
Output:
Output:
6 Python fundamentals| Rooman Technologies