How to Use Dictionary pop() Method in PythonPython Basics


The pop() method removes and returns an element from a dictionary provided the given key.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

dict1 = {'Name': 'Volkswagen', 'Vehicle type': 'SUV','Turbo':'no','Price': 150000,'gearbox': 'automatic-shift'}
print(dict1)
dict1.pop('Vehicle type')
print(dict1)
dict1.pop('Turbo')
print(dict1)

Output:

{'Name': 'Volkswagen', 'Vehicle type': 'SUV', 'Turbo': 'no', 'Price': 150000, 'gearbox': 'automatic-shift'}
{'Name': 'Volkswagen', 'Turbo': 'no', 'Price': 150000, 'gearbox': 'automatic-shift'}
{'Name': 'Volkswagen', 'Price': 150000, 'gearbox': 'automatic-shift'}

Syntax

dictionary.pop(key[, default])

Parameters

Name Description
key The key which is for removal.
default The value to be returned if the key is not in the dictionary.

Return Value

It returns the element removed from the dictionary.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us