Home  >  Article  >  Backend Development  >  How to Delete an Element from a Dictionary in Python?

How to Delete an Element from a Dictionary in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 18:42:02234browse

How to Delete an Element from a Dictionary in Python?

Deleting an Element from a Dictionary in Python

To delete an item from a dictionary in Python, you can use the del statement:

<code class="python">del d[key]</code>

This statement removes the item with the specified key from the dictionary. Note that this statement mutates the original dictionary, so the contents of the dictionary change for any other references to the same instance.

If you want to obtain a new dictionary with the item removed without modifying the original dictionary, you can create a copy of the dictionary and delete the item from the copy:

<code class="python">def removekey(d, key):
    r = dict(d)
    del r[key]
    return r</code>

This function uses the dict() constructor to create a shallow copy of the original dictionary. The copy is then modified to delete the item with the specified key. The function returns the new dictionary.

Note that creating a copy for every dictionary operation (e.g., deletion, assignment) can result in linear time and space complexity, especially for large dictionaries. If you need to perform multiple operations on a large dictionary, consider using a different data structure, such as a HAMT (Hash Array Mapped Trie).

The above is the detailed content of How to Delete an Element from a Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn