![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).
When it is required to generate a dictionary that contains numbers within a given range in a specific form, the input is taken from the user, and a simple ‘for’ loop is used.
Example
Below is a demonstration for the same −
my_num = int(input("Enter a number.. ")) my_dict = dict() for elem in range(1,my_num+1): my_dict[elem] = elem*elem print("The generated elements of the dictionary are : ") print(my_dict)
Output
Enter a number.. 7 The generated elements of the dictionary are : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
Explanation
- The number is taken as user input.
- An empty dictionary is created.
- The number is iterated over.
- The square of the number is stored in the dictionary.
- It is displayed as output on the console.
Advertisements