Python Practice › Dictionary Programs › Program 7
Squares of even, cubes of odd
Write a Python program that stores squares of even numbers and cubes of odd numbers in a dictionary using a comprehension.
Input
[4, 5, 6, 2, 1, 7, 11]
Output
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}Approach
- A conditional expression picks the power.
Solution
numbers = [4, 5, 6, 2, 1, 7, 11]print({n: n ** 2 if n % 2 == 0 else n ** 3 for n in numbers})Output
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}Learn the concept
New to this topic? Read the lesson, then come back.