Store squares of even and cubes of odd numbers in a dictionary using dictionary comprehension.

In this python dictionary program, we will store squares of even and cubes of odd numbers in a dictionary using the dictionary comprehension method.

Steps to solve the program
  1. Take a list as input and create an empty dictionary.
  2. Use for loop to iterate over list elements.
  3. If an element is an even number then store its square and if it is an odd number then store its cube in the dictionary.
  4. Use an if-else statement to check for odd and even numbers.
  5. Print the output.
				
					list1 = [4, 5, 6, 2, 1, 7, 11]
dict1 = {}

for val in list1:
    if val % 2 == 0:
        dict1[val] = val**2
    else:
        dict1[val] = val**3
    
print(dict1)
				
			

Output :

				
					{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}
				
			

create a dictionary from two lists.

clear all items from the dictionary.

Leave a Comment