Delete an element from a dictionary
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).
How can I remove a key from a Python dictionary?
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop()
:
my_dict.pop('key', None)
This will return my_dict[key]
if key
exists in the dictionary, and None
otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')
) and key
does not exist, a KeyError
is raised.
To delete a key that is guaranteed to exist, you can also use:
del my_dict['key']
This will raise a KeyError
if the key is not in the dictionary.
How to delete a value from a dictionary?
I believe you are trying to remove "John" from the list stored in the dictionary. You first have to get a reference to that list, this can be done with the "Player" key. Then you can use the remove
method of the list class to remove an item from it.
An example I think solves your problem is
data = {'Player': ['John','Steffen'], age: [25,26]}
data['Player'].remove('John') # First reference the list, then remove an item from it
I'd take a guess and say the list of ages corresponds to the list of players, so you'd have to also remove John's age from there.
Best method to delete an item from a dict
Use
d.pop
if you want to capture the removed item, like initem = d.pop("keyA")
.Use
del
if you want to delete an item from a dictionary.If you want to delete, suppressing an error if the key isn't in the dictionary:
if thekey in thedict: del thedict[thekey]
What is the best way to remove a dictionary item by value in python?
You can use a simple dict
comprehension:
myDict = {key:val for key, val in myDict.items() if val != 42}
As such:
>>> {key:val for key, val in myDict.items() if val != 42}
{8: 14, 1: 'egg'}
How to remove a KEY from a dictionary in c#
The Remove() method actually deletes an existing key-value pair from a dictionary. You can also use the clear method to delete all the elements of the dictionary.
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
cities.Remove("UK"); // removes UK
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException
if(cities.ContainsKey("France")){ // check key before removing it
cities.Remove("France");
}
cities.Clear(); //removes all elements
You can read this for more information https://www.tutorialsteacher.com/csharp/csharp-dictionary
Remove an item from a dictionary when its key is unknown
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want !=
instead of is not
.
How to remove elements from a Python dictionary based on elements in a list?
I would use a dictionary comprehension to map the keys with the values that aren't found within a list:
new_dict = {k: v for k, v in old_dict.items() if v not in the_list} # filter from the list
Python: Remove item from dictionary in functional way
There is no built-in way for dicts, you have to do it yourself. Something to the effect of:
>>> data = dict(a=1,b=2,c=3)
>>> data
{'a': 1, 'b': 2, 'c': 3}
>>> {k:v for k,v in data.items() if k != item}
Note, Python 3.9 did add a |
operator for dicts to create a new, merged dict:
>>> data
{'a': 1, 'b': 2, 'c': 3}
>>> more_data = {"b":4, "c":5, "d":6}
Then
>>> data | more_data
{'a': 1, 'b': 4, 'c': 5, 'd': 6}
So, similar to +
for list concatenation. Previously, could have done something like:
>>> {**data, **more_data}
{'a': 1, 'b': 4, 'c': 5, 'd': 6}
Note, set
objects support operators to create new sets, providing operators for various basic set operations:
>>> s1 = {'a','b','c'}
>>> s2 = {'b','c','d'}
>>> s1 & s2 # set intersection
{'b', 'c'}
>>> s1 | s2 # set union
{'c', 'a', 'b', 'd'}
>>> s1 - s2 # set difference
{'a'}
>>> s1 ^ s2 # symmetric difference
{'a', 'd'}
This comes down to API design choices.
Related Topics
Python 3 Importerror: No Module Named 'Configparser'
Splitting a List into N Parts of Approximately Equal Length
Why am I Seeing "Typeerror: String Indices Must Be Integers"
Correct Way to Define Python Source Code Encoding
Using Os.Walk() to Recursively Traverse Directories in Python
"Python" Not Recognized as a Command
Checking Multiple Values for a Variable
Comprehensive Beginner's Virtualenv Tutorial
Difference Between _Getattr_ and _Getattribute_
How to State in Requirements.Txt a Direct Github Source
What's the Purpose of "Send" Function on Python Generators
Shared-Memory Objects in Multiprocessing
Catch a Thread's Exception in the Caller Thread
How to Use a Python Script in the Command Line Without Cd-Ing to Its Directory? Is It the Pythonpath
Deprecationwarning: Executable_Path Has Been Deprecated Selenium Python
Stacked Bar Chart with Centered Labels
Access a Function Variable Outside the Function Without Using "Global"