How to Remove a Key from a Python Dictionary

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.

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).

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.

Removing multiple keys from a dictionary safely

Why not like this:

entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
for key in entries:
if key in the_dict:
del the_dict[key]

A more compact version was provided by mattbornski using dict.pop()

Change the name of a key in dictionary

Easily done in 2 steps:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1

Remove key from dictionary in Python returning new dictionary

How about this:

{i:d[i] for i in d if i!='c'}

It's called Dictionary Comprehensions and it's available since Python 2.7.

or if you are using Python older than 2.7:

dict((i,d[i]) for i in d if i!='c')

Python: how to remove a value from a dict if it exactly matches the key?

You can use a one-liner with both dictionary comprehension and list comprehension:

result = {k:[vi for vi in v if k != vi] for k,v in jumps.items()}

This results in:

>>> {k:[vi for vi in v if k != vi] for k,v in jumps.items()}
{'T8': ['T6', 'S6'], 'I6': ['H6', 'I5']}

Note that you will remove all elements from the lists that are equal to the key. Furthermore the remove process is done for all keys.

The code works as follows: we iterate over every key-value pair k,v in the jumps dictionary. Then for every such pair, we construct a key in the resulting dictionary, and associate [vi for vi in v if k != vi] with it. That is a list comprehension where we filter out all values of v that are equal to k. So only the vis remain (in that order) that are k != vi.

How to delete key value pair of a dictionary inside a dictionary?

or to stay closer to what you did and delete the key 67 from all inner dictionaries without needing to know theire keys as well:

will work for python 2.7

dicto = {12:{34:45,56:78},45:{67:23,90:15}}
print ""
for k,v in dicto.items():
for i in v.items():
if (i[0] == 67):
v.pop(i[0])
print(dicto)

Output:

{12: {56: 78, 34: 45}, 45: {90: 15}}

Instead of modifying some element you tell the correct inner dict to remove its key/value pair from itself

This code will remove the key ``67` from ALL inner dictionaries:

dicto = {12:{34:45,56:78},45:{67:23,90:15},99:{67:1,88:5}}

will lead to

{99: {88: 5}, 12: {56: 78, 34: 45}, 45: {90: 15}}

Edit:
As Souvik Rey pointed out, this wont work for 3.6 (tested it with pyfiddle for 2.7 where it works)

will work with 3.6

dicto = {12:{34:45,56:78},45:{67:23,90:15},99:{67:1,88:5}}
print ("")
dictsToRemoveKeysFrom = []
for k,v in dicto.items():
print (v)
for i in v.items():
if (i[0] == 67):
dictsToRemoveKeysFrom.append(v)

for d in dictsToRemoveKeysFrom:
d.pop(67)

print(dicto)

You get the error because you alter the dictionarys while iterating over theire parent. Simply remember the dicts to modify and modify them afterwards.



Related Topics



Leave a reply



Submit