Python Program to Create Dictionary of keys and values are square of keys

Write a Python Program to Create Dictionary of keys and values are square of keys with a practical example.

Python Program to Create Dictionary of keys and values are square of keys Example 1

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 exponent operator.

# Python Program to Create Dictionary of keys and values are square of keys

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

for x in range(1, number + 1):
    myDict[x] = x ** 2
    
print("\nDictionary = ", myDict)
Python Program to Create Dictionary of keys and values are square of keys 1

In this Python example, number = 5.

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

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

Do the Same for the remaining for loop iterations

Program to Create Dictionary of keys from 1 to n and values are square of keys Example 2

This python code to Create Dictionary of keys and values are square of keys is another approach.

# Python Program to Create Dictionary of keys and values are square of keys

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

myDict = {x:x ** 2 for x in range(1, number + 1)}
    
print("\nDictionary = ", myDict)

Output of a Dictionary of keys and square of keys as values

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}
>>>