Julie has created a dictionary containing names and marks as key value pairs of 6 students. Write a program, with separate user defined functions to perform the following operations: 

  • Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 75. 

Pop and display the content of the stack. 

For example: If the sample content of the dictionary is as follows:

R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82} 

The output from the program should be: TOM ANU BOB OM

 

Answer

Slide35.JPG

Slide36.JPG
Slide37.JPG Slide38.JPG

Program:

myDict = {"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}        #creating a dictionary

 

def func_push(stack, name):

    stack.append(name)      #it appends the received name(key) to the stack

 

def func_pop(stack):

    if stack != []:

        return stack.pop()      #return the topmost name if stack is not empty

    else:

        return None

     

myStack = []

for i in myDict:        #with each iteration,i represents each key(name) of myDict dictionary(key value pairs)

 

    if myDict[i] >= 75:     #myDict[i] represents values of myDict dictionary(key value pairs)

 

        func_push(myStack, i)       #if value of key value pair is >=75,then name(key) is pushed in stack

 

while True:

    if myStack != []:       #check if the stack is empty or not

        print(func_pop(myStack), end = " ")     #if not empty, then pop out content of stack

    else:

        break

 

Output:

TOM ANU BOB OM

Remove Ads
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.