w3resource

Python: Print a dictionary where the keys are numbers between 1 and 15 and the values are square of keys


7. Dictionary with Keys 1 to 15 and Their Squares

Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are the square of the keys.

Sample Solution:-

Python Code:

# Create an empty dictionary 'd' to store the squares of numbers.
d = dict()

# Iterate through numbers from 1 to 15 (inclusive).
for x in range(1, 16):
    # Calculate the square of each number and store it in the dictionary 'd' with the number as the key.
    d[x] = x ** 2

# Print the dictionary 'd' containing the squares of numbers from 1 to 15.
print(d)
 

Sample Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 
225} 

Flowchart:

Flowchart: Print a dictionary where the keys are numbers between 1 and 15 and the values are square of keys

For more Practice: Solve these Related Problems:

  • Write a Python script to create a dictionary with keys from 1 to 15 and their squares as values using a loop.
  • Write a Python script to generate this dictionary using dictionary comprehension and then print it sorted by key.
  • Write a Python script to modify the dictionary so that the values are the cubes of the keys instead of squares.
  • Write a Python script to use a function to build a dictionary for numbers 1 to n and then test it with n=15.

Python Code Editor:

Previous: Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
Next: Write a Python script to merge two Python dictionaries.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.