Python: Print a dictionary where the keys are numbers between 1 and 15 and the values are square of keys
Python dictionary: Exercise-7 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics