Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form

Write a Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form with a practical example.

Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form Example

In this python program we are using using for loop to iterate from 1 to user specified value. Within the Python for loop, we are assigning values for Dictionary by using * operator.

# Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form

number = int(input("Please enter the Maximum Number : "))
myDict = {}

for x in range(1, number + 1):
    myDict[x] = x * x
    
print("\nDictionary = ", myDict)
Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form or series

In this python program, Given number = 5.

First Iteration x will be 1 : for 1 in range(1, 6)
myDict[x] = x * x
myDict[1] = 1 * 1 = 1

Second Iteration x will be 2 : for 2 in range(1, 6)
myDict[2] = 2 * 2 = 4

Do the Same for the remaining for loop iterations

Python Program to generate Dictionary of Numbers 1 to n in the form of (x, x*x) Example 2

This is another Python approach of creating dictionary. Here, we are using single line to generate Dictionary of numbers in the form of x, x*x. Please refer to * Arithmetic operator.

# Python Program to Create Dictionary of Numbers 1 to n in (x, x*x) form

number = int(input("Please enter the Maximum Number : "))

myDict = {x:x * x for x in range(1, number + 1)}

print("\nDictionary = ", myDict)

Generate dictionary in the for x, x* x output

Please enter the Maximum Number : 6

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
>>> 
Please enter the Maximum Number : 9

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>>