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 range()
Python staticmethod()
Python time Module
Python String join()
Python Object Oriented Programming
Python Program to Randomly Select an Element From the List
Python Dictionary items()
Python format()
Python open()
Python id()
Python globals()
Python Set difference_update()
Python Program to Find Hash of File
Python isinstance()
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Find the Factors of a Number
Python bin()
Python oct()
Python String rjust()
Python Program to Find the Size (Resolution) of a Image
Python Program to Count the Number of Digits Present In a Number
Python Directory and Files Management
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python super()
Python del Statement
Python Set pop()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python String index()
Python dict()
Python __import__()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho