Push the names of students who scored above 75 from a dictionary onto a stack and pop them
Expt. No.16
Page No.32
Stack from a dictionary
Aim
To write a Python program with functions push_names(d), which pushes the names of students with marks above 75 from a dictionary onto a stack, and pop_all(), which pops and displays them until the stack is empty.
Concepts used
Algorithm
- Store students and marks in a dictionary.
- push_names(d): for each key, if its value is above 75, push the key onto the stack.
- pop_all(): pop and display items while the stack is not empty, then display "Stack is empty".
Program
# Push names with marks above 75 onto a stack, then pop them marks = {"Asha": 82, "Rohan": 67, "Kabir": 91, "Diya": 76, "Neel": 58}stack = [] def push_names(d): for name in d: if d[name] > 75: stack.append(name) def pop_all(): while stack != []: print(stack.pop(), end=" ") print() print("Stack is empty") push_names(marks)print("Stack after pushing:", stack)print("Popped:", end=" ")pop_all()
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python stack_from_dictionary.py
Stack after pushing: ['Asha', 'Kabir', 'Diya']
Popped: Diya Kabir Asha
Stack is empty
✓ Printed by running this program, not typed by hand.
Result
Asha, Kabir and Diya (marks above 75) were pushed in dictionary order and popped in reverse order: Diya, Kabir, Asha.
Viva voce: what the examiner may ask
01In what order are the names popped and why?
In reverse order of pushing, because the last item pushed is on top (LIFO).
02What does while stack != [] check?
That the stack still has items; an empty list ends the loop.
03What does iterating over a dictionary give?
Its keys, here the names.
Variations for the lab test
- Push the marks instead of the names and pop them.
- Push the names of students who scored below 60.
- Write a function that returns the top element without removing it.
! Common mistake Printing the stack list directly instead of popping does not empty the stack, so the question's "pop until empty" is not done.