Home >Backend Development >Python Tutorial >How to Remove Elements from a Python Dictionary: Del or Shallow Copy?
Delete an Element from a Dictionary
When working with dictionaries in Python, there may come a time when you need to remove an element. This can be achieved in two ways:
1. Modifying the Original Dictionary
Using the del statement, you can directly remove an element from the dictionary, thereby modifying the original dictionary:
<code class="python">del d[key]</code>
where d is the dictionary and key is the key of the element to be removed.
2. Obtain a New Dictionary without the Element
To obtain a new dictionary with the element removed, without modifying the original dictionary, you can use the following method:
<code class="python">def removekey(d, key): r = dict(d) del r[key] return r</code>
This function first creates a copy of the original dictionary d using the dict() constructor. Then, it removes the specified key from the copy and returns the modified copy r as a new dictionary.
Note:
The above is the detailed content of How to Remove Elements from a Python Dictionary: Del or Shallow Copy?. For more information, please follow other related articles on the PHP Chinese website!