Dictionary Number Squares,

Write a Python program to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).

Example 1:

Input: 5 
Output: {1:1, 2:4, 3:9, 4:16, 5:25}

Example 2:

Input: 3 
Output: {1:1, 2:4, 3:9}

You can use a dictionary comprehension to solve this problem.

def generate_dict(n):
    return {i : i*i for i in range(1, n+1)}

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!