Skip to content
Fix Code Error

Delete an element from a dictionary

March 13, 2021 by Code Error
Posted By: Anonymous

Is there a way to delete an item from a dictionary in Python?

Additionally, how can I delete an item from a dictionary to return a copy (i.e., not modifying the original)?

Solution

The del statement removes an element:

del d[key]

Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:

def removekey(d, key):
    r = dict(d)
    del r[key]
    return r

The dict() constructor makes a shallow copy. To make a deep copy, see the copy module.


Note that making a copy for every dict del/assignment/etc. means you’re going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you’re planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).

Answered By: Anonymous

Related Articles

  • Combining items using XSLT Transform
  • How to prevent scrolling the whole page?
  • How do I merge two dictionaries in a single…
  • Can't install via pip because of egg_info error
  • What's the difference between eval, exec, and compile?
  • Is it safe to shallow clone with --depth 1, create…
  • Python - How to assign/map non-sequential JSON…
  • Understanding dict.copy() - shallow or deep?
  • Copy a variable's value into another
  • bootstrap-datepicker in dd/mm/yyyy - selected date…
  • Are dictionaries ordered in Python 3.6+?
  • How to "perfectly" override a dict?
  • data.table vs dplyr: can one do something well the…
  • Usage of __slots__?
  • Best way to replace multiple characters in a string?
  • How to update Python?
  • How not to get a repeated attribute of an object?
  • What are type hints in Python 3.5?
  • How does PHP 'foreach' actually work?
  • vue-test-utils setup getting TypeError: Cannot…
  • What is the copy-and-swap idiom?
  • Change URl without page refresh NEXT.JS
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • When dealing with Localizable.stringsdict, why…
  • Get the name of an object's type
  • integrating disqus with emberjs only works on first…
  • What does Ruby have that Python doesn't, and vice versa?
  • Undefined Reference to
  • Fastest way to list all primes below N
  • Combining pyOSC with pyQT5 / Threading?
  • Install pip in docker
  • What is move semantics?
  • How to create dictionary and add key–value pairs…
  • Dynamically allocating an array of objects
  • How does the @property decorator work in Python?
  • Smart way to truncate long strings
  • More elegant way of declaring multiple variables at…
  • What is The Rule of Three?
  • Implement LRU cache with using…
  • Convert array to nested JSON object - Angular Material tree
  • Best way to communicate between instances of the…
  • NextJS - can't identify where state change is…
  • Relative imports for the billionth time
  • What is a NullReferenceException, and how do I fix it?
  • Delete all objects in a list
  • Manually raising (throwing) an exception in Python
  • Elegant ways to support equivalence ("equality") in…
  • typescript - cloning object
  • How to fix Invalid byte 1 of 1-byte UTF-8 sequence
  • How do I use /deep/ or >>> or ::v-deep in Vue.js?
  • How to return a negative fraction when subtracting…
  • Deep Cloning Backbone.js Models
  • How to add 'load more' functionality to items on a…
  • Simple Vue.js Computed Properties Clarification
  • How to deep copy a list?
  • Making a map of composite types typescript
  • How to make a Tkinter Button change its own text attribute?
  • What is the difference between a deep copy and a…
  • Change route without reloading page with Next.js
  • Creating a singleton in Python
  • Implement javascript instance store by returning…
  • Display Grid does not work in Polymer correctly
  • TypeError: 'type' object is not subscriptable when…
  • How do you create nested dict in Python?
  • java.sql.SQLException: - ORA-01000: maximum open…
  • angular - override mat-form-field inherited styles
  • Deep cloning objects
  • Add Keypair to existing EC2 instance
  • Next.js: one page that match root '/' and dynamic…
  • Shallow routing using withRouter and custom server…
  • Python3 asyncio: Process tasks from dict and store…
  • How do I turn a nested dict of lists (with dicts)…
  • TypeError: 'str' object is not callable (Python)
  • What is the most efficient way to deep clone an…
  • What is the difference between dict.items() and…
  • When is del useful in Python?
  • How to Deep clone in javascript
  • How To Check A Radio Button in Vue.JS 2 WITHOUT…
  • Reference - What does this regex mean?
  • Copy specified number of lines to multiple documents…
  • Problems with local variable scope. How to solve it?
  • PyYaml: cannot access nested instance attributes…
  • Kivy WebView Error: Cannot add to window, it already…
  • How to get string objects instead of Unicode from JSON?
  • When should iteritems() be used instead of items()?
  • Debugging Javascript (Backbone and Marionette)
  • Convert Django Model object to dict with all of the…
  • Call a method from a method of another class (Nested Class)
  • Centering in CSS Grid
  • Does Vue.js have a built in way to add a copy of a…
  • Polymer: Animating iron-selector with neon-animation
  • Angular 2 - innerHTML styling
  • Global Events in Angular
  • Various ways to remove local Git changes
  • Keras Sequential API is replacing every layer with…
  • Checkout another branch when there are uncommitted…
  • Understanding constraints in agrep fuzzy matching in R
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Styling mat-select in Angular Material
  • Polymer Paper-Input not working or rendering

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Save plot to image file instead of displaying it using Matplotlib

Next Post:

How to style a checkbox using CSS

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error