Python Program to Delete an Element From a Dictionary – 2024

Hey guys, in this blog we will see a Python Program to Delete an Element From a Dictionary.

Table of Contents

Example 1: Using the del keyword

# Python Program to Delete an Element From a Dictionary

my_dict = {1: 'machine', 2: 'learning', 3: 'projects'}

del my_dict[3]

print(my_dict)

Output

{1: 'machine', 2: 'learning'}
  • Here we have used del keyword to delete a key-value pair from our dictionary.
  • We can do similar for a list also.

Example 2: Using pop()

# Delete an Element From a Dictionary

my_dict = {1: 'machine', 2: 'learning', 3: 'projects'}

print(my_dict.pop(3))

print(my_dict)

Output

projects
{1: 'machine', 2: 'learning'}
  • We can also use pop() to delete a key-value pair from a dictionary.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *