Languages
[Edit]
EN

Python - remove dictionary items

0 points
Created by:
evangeline
420

In this article, we would like to show you how to remove dictionary items in Python.

Quick solution:

my_dict = {
    "id": 1,
    "name": "Tom",
    "age": 25
}

my_dict.pop("age")

 

1. Practical example using pop() method

In this example, we use pop() method that removes the item with specified key name.

my_dict = {
    "id": 1,
    "name": "Tom",
    "age": 25
}

my_dict.pop("age")

print(my_dict.items())  # [('id', 1), ('name', 'Tom')]

Output:

dict_items([('id', 1), ('name', 'Tom')])

2. Using popitem() method

In this example, we use popitem() method that removes the last inserted item.

my_dict = {
    "id": 1,
    "name": "Tom",
    "age": 25
}

my_dict.popitem()

print(my_dict.items())  # [('id', 1), ('name', 'Tom')]

Output:

dict_items([('id', 1), ('name', 'Tom')])

Note:

In versions earlier than Python 3.7 the popitem() method removes random item instead.

3. Using del keyword

In this example, we use del keyword that removes item with the specified key name.

my_dict = {
    "id": 1,
    "name": "Tom",
    "age": 25
}

del my_dict["age"]

print(my_dict.items())  # [('id', 1), ('name', 'Tom')]

Output:

dict_items([('id', 1), ('name', 'Tom')])

4. Clear the dictionary

In this example, we use clear() method to empty the dictionary.

my_dict = {
    "id": 1,
    "name": "Tom",
    "age": 25
}

my_dict.clear()

print(my_dict.items())  # []

Output:

dict_items([])

Alternative titles

  1. Python - pop dictionary items
  2. Python - delete dictionary items
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - dictionary (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join