Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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. This creates key−value pairs where each number maps to its square.
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}
Alternative Methods
Using Dictionary Comprehension
A more concise approach using dictionary comprehension −
n = 7
square_dict = {x: x * x for x in range(1, n + 1)}
print("Dictionary using comprehension:")
print(square_dict)
Dictionary using comprehension:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
Using zip() and range()
Another approach combining zip() with range() −
n = 5
numbers = range(1, n + 1)
squares = [x * x for x in numbers]
result_dict = dict(zip(numbers, squares))
print("Dictionary using zip:")
print(result_dict)
Dictionary using zip:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation
- The number is taken as user input.
- An empty dictionary is created.
- The number is iterated over using
range(1, my_num + 1). - The square of each number is stored as the value in the dictionary.
- The result is displayed on the console.
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | High | Good | Beginners |
| Dict Comprehension | Medium | Better | Concise code |
| zip() Method | Medium | Good | Complex transformations |
Conclusion
Dictionary comprehension provides the most concise solution for creating number−square mappings. Use the for loop approach for better readability, especially when learning Python fundamentals.
Advertisements
