Squares of even, cubes of odd

EasyDictionary Programs · 7 of 94

Write a Python program that stores squares of even numbers and cubes of odd numbers in a dictionary using a comprehension.

Advertisement
Input
[4, 5, 6, 2, 1, 7, 11]
Output
{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}

Approach

  1. A conditional expression picks the power.

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment