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
- Take a list as input and create an empty dictionary.
- Use for loop to iterate over list elements.
- 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.
- Use an if-else statement to check for odd and even numbers.
- 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}