;

Python Program to Create the Dictionary of Keys and Values Are Square of Keys


Tutorialsrack 08/05/2020 Python

In this python program, we will learn how to create the dictionary of keys and values are square of the key.

Here is the source code of the program to create the dictionary of keys and values are square of the key.

Program 1: Python Program to Create the Dictionary of Keys and Values Are Square of Keys Using For Loop

Python Program to Create the Dictionary of Keys and Values Are Square of Keys Using For Loop
# Python Program to Create the Dictionary of Keys and Values
# Are Square of Keys Using For Loop

# Take the Input from the User
number = int(input("Enter the Maximum Number: "))
myDict = {}

for x in range(1, number + 1):
    myDict[x] = x ** 2
    
# Print the Output
print("\nDictionary = ", myDict)
Output

Enter the Maximum Number: 5

 

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Program 2: Another Approach to Create the Dictionary of keys and values are square of keys

Another Approach to Create the Dictionary of keys and values are square of keys
# Another Approach to Create the Dictionary of keys and values are square of keys

# Take the Input from the User
number = int(input("Enter the Maximum Number : "))

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

# Print the Output
print("\nDictionary = ", myDict)
Output

Enter the Maximum Number : 6

 

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}


Related Posts



Comments

Recent Posts
Tags