Dictionary of cubes

EasyDictionary Programs · 20 of 94

Write a Python program to create {k: k³} for k from 1 to n.

Advertisement
Input
n = 4
Output
{1: 1, 2: 8, 3: 27, 4: 64}

Approach

  1. A dict comprehension over range(1, n + 1).

Solution

Python
n = 4print({k: k ** 3 for k in range(1, n + 1)})
Output
{1: 1, 2: 8, 3: 27, 4: 64}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs