Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).

PythonServer Side ProgrammingProgramming

When it is required to generate a dictionary that contains numbers within a given range in a specific form, the input is taken from the user, and a simple ‘for’ loop is used.


Below is a demonstration for the same −

 Live Demo

my_num = int(input("Enter a number.. "))
my_dict = dict()
for elem in range(1,my_num+1):
   my_dict[elem] = elem*elem
print("The generated elements of the dictionary are : ")


Enter a number.. 7

The generated elements of the dictionary are :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}


  • The number is taken as user input.
  • An empty dictionary is created.
  • The number is iterated over.
  • The square of the number is stored in the dictionary.
  • It is displayed as output on the console.
Published on 12-Mar-2021 17:16:24