Python remove items from dict

Remove an item from a dictionary in Python (clear, pop, popitem, del)

In Python, to remove an item (element) from a dictionary ( dict ), use the clear() , pop() , popitem() methods or the del statement. You can also remove items that satisfy the conditions using the dictionary comprehensions.

See the following article for how to add items to a dictionary.

Remove all items from a dictionary: clear()

The clear() method removes all items from a dictionary, making it empty.

d = 'k1': 1, 'k2': 2, 'k3': 3> d.clear() print(d) # <> 

Remove an item by a key and return its value: pop()

By specifying a key to the pop() method, the item is removed and its value is returned.

d = 'k1': 1, 'k2': 2, 'k3': 3> removed_value = d.pop('k1') print(d) # print(removed_value) # 1 

By default, specifying a non-existent key raises a KeyError .

d = 'k1': 1, 'k2': 2, 'k3': 3> # removed_value = d.pop('k4') # print(d) # KeyError: 'k4' 

If you pass the second argument, its value is returned if the key does not exist. The dictionary remains unchanged.

d = 'k1': 1, 'k2': 2, 'k3': 3> removed_value = d.pop('k4', None) print(d) # print(removed_value) # None 

Remove an item and return its key and value: popitem()

The popitem() method removes an item from the dictionary and returns its key and value as a tuple, (key, value) .

Since Python 3.7, the order of elements in the dictionary is preserved. As a result, popitem() removes elements in LIFO (last in, first out) order.

A KeyError is raised for an empty dictionary.

d = 'k1': 1, 'k2': 2> k, v = d.popitem() print(k) print(v) print(d) # k2 # 2 # k, v = d.popitem() print(k) print(v) print(d) # k1 # 1 # <> # k, v = d.popitem() # KeyError: 'popitem(): dictionary is empty' 

Remove an item by a key from a dictionary: del

You can also use the del statement to delete an item from a dictionary.

d = 'k1': 1, 'k2': 2, 'k3': 3> del d['k2'] print(d) # 

You can specify and remove multiple items.

d = 'k1': 1, 'k2': 2, 'k3': 3> del d['k1'], d['k3'] print(d) # 

If a non-existent key is specified, a KeyError is raised.

d = 'k1': 1, 'k2': 2, 'k3': 3> # del d['k4'] # print(d) # KeyError: 'k4' 

Remove items that satisfy a condition: Dictionary comprehensions

To remove items that meet certain conditions from a dictionary, use dictionary comprehensions, which are the dictionary equivalent of list comprehensions.

«Removing items that satisfy a condition» is equivalent to «extracting items that do not satisfy the condition».

For example, to remove items with odd values, you can extract items with even values. The same applies to the opposite case.

d = 'apple': 1, 'banana': 10, 'orange': 100> dc = k: v for k, v in d.items() if v % 2 == 0> print(dc) # dc = k: v for k, v in d.items() if v % 2 == 1> print(dc) # 

The items() method of dict is used to extract keys and values.

You can also specify conditions based on the keys.

dc = k: v for k, v in d.items() if k.endswith('e')> print(dc) # dc = k: v for k, v in d.items() if not k.endswith('e')> print(dc) # 

You can use and and or to specify multiple conditions.

dc = k: v for k, v in d.items() if v % 2 == 0 and k.endswith('e')> print(dc) # 

Источник

How to Remove an Element From Dictionary in Python

Method 1: Using the “del” statement

To remove an element from a dictionary using the del statement, “specify the key of the element you want to remove after the del keyword”. The element with the specified key will be removed from the dictionary. If the key is not found in the dictionary, a KeyError will be raised.

Example

main_dict = # Remove the element with the key 'B' del main_dict['B'] print(main_dict)

Method 2: Using the “dict.pop()” method

The “dict.pop()” method allows you to remove an element with a specified key and return its value. You must pass the key of the element you want to remove as an argument to the pop() method.

If the key is not found in the dictionary, a KeyError will be raised. However, you can also provide a default value as a second argument to the pop() method, which will be returned instead of raising a KeyError when the key is not found in the dictionary.

Example

main_dict = # Remove the element with the key 'B' main_dict.pop('B') print(main_dict)

The “dict.pop()” method removes the element with the specified key and returns its value. If the key is not found, a KeyError will be raised.

main_dict = # Remove the element with the key 'B' main_dict.pop('D') print(main_dict) 
KeyError: 'D'

Method 3: Using the popitem() method

The popitem() method “removes an element from the dictionary and returns its key and value as a tuple, (key, value).”

Example

cars = cars.popitem() print(cars)

Method 4: Using the clear() method

The clear() method removes all elements from a dictionary, making it empty.

Example

cars = cars.clear() print(cars)

Источник

Python Removing Items from a Dictionary

There are several methods to remove items from a dictionary:

Example

The pop() method removes the item with the specified key name:

Example

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

Example

The del keyword removes the item with the specified key name:

Example

The del keyword can also delete the dictionary completely:

thisdict = <
«brand»: «Ford»,
«model»: «Mustang»,
«year»: 1964
>
del thisdict
print(thisdict) #this will cause an error because «thisdict» no longer exists.

Example

The clear() keyword empties the dictionary:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Remove Item from Dictionary Python

In this tutorial, we will learn 5 different ways to remove an item from a dictionary in Python with examples.

Remove Item from Dictionary Python

  • Introduction
  • Method 1: Using pop() method
  • Method 2: Using del keyword
  • Method 3: Using popitem() method
  • Method 4: Using dict comprehension
  • Method 5: Using clear() method
  • Conclusion
  • Introduction

    A dictionary is a collection of key-value pairs, used to store data values like a map or associative array.

    Python dictionaries are mutable, meaning that we can change, add or remove items after the dictionary has been created.

    There are several ways to remove items from a dictionary, here we will see 5 of them with various examples.

    Method 1: Using pop() method

    The pop() is a built-in method in Python for dictionaries that removes the item with the specified key name.

    dict.pop(keyname, defaultvalue) # or simply dict.pop(keyname)

    Here, keyname is the key name of the item you want to remove, and defaultvalue is the value to return if the key does not exist.

    Remove item from the dictionary:

    dict1 = print("Before:", dict1) # remove item with key name "age" dict1.pop("age") print("After:", dict1) # remove item with key name "country" dict1.pop("country") print("Again After:", dict1)

    Here, we have created a dictionary with 3 key-value pairs, and then we removed the item with key names «age» and «country» using the pop() method.

    Method 2: Using del keyword

    The del keyword has wide usage in Python, like deleting variables, deleting items from a list, deleting items from a dictionary, etc.

    To delete or remove an item from a dictionary, use the del keyword, followed by the dictionary name, and the key name of the item you want to remove.

    For example, del dict1[«age»] will remove the item with the key name «age» from the dictionary dict1 .

    Remove item from the dictionary:

    dict1 = print("Before:", dict1) # using del keyword del dict1["age"] print("After:", dict1) del dict1["country"] print("Again After:", dict1)

    Note: If the key does not exist, both pop() and del will raise an error.

    Method 3: Using popitem() method

    The popitem() method removes the last inserted item from the dictionary (in versions before 3.7, a random item is removed instead).

    Remove the last inserted item from the dictionary:

    fruits = print("Before:", fruits) # remove last inserted item fruits.popitem() print("After:", fruits)

    Here, we have created a dictionary with 3 key-value pairs, and then we removed the last inserted item using the popitem() method.

    Note: If the dictionary is empty, popitem() will raise an error.

    Method 4: Dictionary comprehension

    Dictionary comprehension is a technique to create a new dictionary from an iterable object (like a list, tuple, set, etc.).

    We can use it to filter out items from a dictionary that we don’t want to keep or remove items from a dictionary.

    Remove items from the dictionary:

    fruits = print("Before:", fruits) # remove items with the value "green" new_fruits = print("After:", new_fruits)

    Method 5: Using clear() method

    The clear() method removes all the items from the dictionary and clears the dictionary.

    For example, dict1.clear() will remove all the items from the dictionary dict1 .

    person = print("Before:", person) # using clear() method person.clear() print("After:", person)

    All the items are removed from the dictionary, and the dictionary is cleared.

    Alternatively, you can directly assign an empty dictionary to the dictionary variable to clear the dictionary.

    person = # clear a dictionary # method 1 person.clear() # method 2 person = <> # method 3 person = dict()

    Frequency Asked Questions

    1. How do you delete a specific value in a dictionary? There are several ways to delete a specific value from a dictionary. You can use the pop() method, del keyword, or dictionary comprehension.
    2. How do I remove all elements from a dictionary? You can use the clear() method to remove all the elements from a dictionary.

    Conclusion

    Now you have 5 different ways to remove items from a dictionary in Python. You can use any of these methods as per your requirement.

    Here is a quick recap of all the methods:

    • pop() method
    • del keyword
    • popitem() method
    • Dictionary comprehension
    • clear() method

    Источник

    Читайте также:  Html form input type submit value
    Оцените статью