Table of Contents
In this tutorial, we will learn about the Python Dictionary pop() method with the help of examples.
The pop() method removes and returns an element from a dictionary having the given key.
Example
# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }
element = marks.pop('Chemistry')
print('Popped Marks:', element)
# Output: Popped Marks: 72
1. Syntax of Dictionary pop()
The syntax of pop() method is
dictionary.pop(key[, default])
2. pop() Parameters
pop() method takes two parameters:
- key – key which is to be searched for removal
- default – value which is to be returned when the key is not in the dictionary
3. Return value from pop()
The pop() method returns:
- If
keyis found – removed/popped element from the dictionary - If
keyis not found – value specified as the second argument (default) - If
keyis not found and default argument is not specified –KeyErrorexception is raised
4. Example 1: Pop an element from the dictionary
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('apple')
print('The popped element is:', element)
print('The dictionary is:', sales)
Output
The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}
5. Example 2: Pop an element not present from the dictionary
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('guava')
Output
KeyError: 'guava'
6. Example 3: Pop an element not present from the dictionary, provided a default value
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('guava', 'banana')
print('The popped element is:', element)
print('The dictionary is:', sales)
Output
The popped element is: banana
The dictionary is: {'orange': 3, 'apple': 2, 'grapes': 4}
Related posts:
Python Program Read a File Line by Line Into a List
Python hex()
Python String isdigit()
Python String isnumeric()
Python Program to Calculate the Area of a Triangle
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String join()
Python String count()
Python divmod()
Python Program to Find HCF or GCD
Python Program to Add Two Numbers
Python String isupper()
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Remove Duplicate Element From a List
Python Set clear()
Python Iterators
Python issubclass()
Python List copy()
Python datetime
Python String endswith()
Python List reverse()
Python Program to Return Multiple Values From a Function
Python Program to Check if a Number is Positive, Negative or 0
Python Exception Handling Using try, except and finally statement
Python Tuple index()
Python Dictionary popitem()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python set()
Python Global Keyword
Python Program to Convert Two Lists Into a Dictionary
Python Program to Check Leap Year
Python List sort()