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'}
Remove Item in Dictionary based on Value
Are you trying to remove a single value or all matching values?
If you are trying to remove a single value, how do you define the value you wish to remove?
The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
If you wish to remove all matching instances of the same value, you can do this:
foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
dic.Remove(item.Key);
}
And if you wish to remove the first matching instance, you can query to find the first item and just remove that:
var item = dic.First(kvp => kvp.Value == value);
dic.Remove(item.Key);
Note: The ToList()
call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.
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 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
Removing entries from a dictionary based on values
You can use a dict comprehension:
>>> { k:v for k, v in hand.items() if v }
{'m': 1, 'l': 1}
Or, in pre-2.7 Python, the dict
constructor in combination with a generator expression:
>>> dict((k, v) for k, v in hand.iteritems() if v)
{'m': 1, 'l': 1}
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 remove elements from lists in dictionaries based on condition in python
You are not accessing the lists correctly. You would want to do:
del cat_map[k][cat_map[k].index(item)]
but you could simplify this check by:
for k,v in cat_map.items():
if k in v:
v.remove(k)
How to delete a key and its values from a dictionary based on its position Python
How to remove a key by position
There is not a direct API for indexing dictionaries, but you can list the keys, select a key by position and then remove it from the dictionary.
def remove_key(d, i):
'Mutate the dictionary to remove i-th key'
keys = d.keys()
del d[keys[i]]
return d
Specific case for "double-ups"
If you data is doubled-up, a dictionary will eliminate the duplicates before you can get to the pairs. So, the data needs to be stored as a list of key/value pairs rather than as a dictionary. That will also allow you to directly delete by position:
>>> receipt = [('beef', 'mint'), ('beef', 'chips'), ('chicken', 'chips')]
>>> del receipt[1]
>>> receipt
[('beef', 'mint'), ('chicken', 'chips')]
Remove a dictionary key that has a certain value
Modifying the original dict:
for k,v in your_dict.items():
if v == 'DNC':
del your_dict[k]
or create a new dict using dict comprehension:
your_dict = {k:v for k,v in your_dict.items() if v != 'DNC'}
From the docs on iteritems()
,iterkeys()
and itervalues()
:
Using
iteritems()
,iterkeys()
oritervalues()
while adding or
deleting entries in the dictionary may raise aRuntimeError
or fail
to iterate over all entries.
Same applies to the normal for key in dict:
loop.
In Python 3 this is applicable to dict.keys()
, dict.values()
and dict.items()
.
Related Topics
Wpf Binding Not Updating the View
Can You Access UI Elements from Another Thread? (Get Not Set)
Why am I Getting 'One or More Types Required to Compile a Dynamic Expression Cannot Be Found.'
Check for Any Element That Exists in Two Collections
Field Initializer in C# Class Not Run When Deserializing
Ghost-Borders ('Ringing') When Resizing in Gdi+
MVC 5 Dynamic Rows with Begincollectionitem
Multiple Controller Types with Same Route Prefix ASP.NET Web API
Synchronizationlockexception on Monitor.Exit When Using Await
C# Form.Transparencykey Working Different for Different Colors, Why
How to Change the Culture of a Winforms Application at Runtime
Why Gettype Returns System.Int32 Instead of Nullable<Int32>
Print Fixeddocument/Xps to PDF Without Showing File Save Dialog