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.