Define a function that can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are squares of keys

Question:

Define a function that can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are squares of keys.

Hints:

  • Use dict[key]=value pattern to put entry into a dictionary.
  • Use the ** operator to get the power of a number.
  • Use range() for loops.

Solution:

def printDict():
	d=dict()
	for i in range(1,21):
		d[i]=i**2
	print d
		

printDict()
Code language: Python (python)

Leave a Comment