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 = {}

# iterate through the list of values
for val in list1:
    # val is divisible by 2, then value is even number
    if val % 2 == 0:
        # dict store value as square
        dict1[val] = val**2
    else:
        # dict store value as cube
        dict1[val] = val**3
    
print("result dictionary:", dict1)
				
			

 Output :

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


Solution 2: solution with dictionary comprehension.
				
					input_list = [4, 5, 6, 2, 1, 7, 11]
dict_result={x:x**2 if x%2==0 else x**3 for x in input_list}
print("output dictionary :", dict_result)
				
			
 
Output:
				
					output dictionary : {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