简体   繁体   中英

How can I remove a key from a Python dictionary?

Is there a one-line way of deleting a key from a dictionary without raising a KeyError ?

if 'key' in my_dict:
    del my_dict['key']

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 (ie 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.

Specifically to answer "is there a one line way of doing this?"

if 'key' in my_dict: del my_dict['key']

...well, you asked ;-)

You should consider, though, that this way of deleting an object from a dict is not atomic —it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError . Given this, it would be safest to either use dict.pop or something along the lines of

try:
    del my_dict['key']
except KeyError:
    pass

which, of course, is definitely not a one-liner.

It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default . If default is not given and key is not in the dictionary, a KeyError is raised.

Documentation

del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists

>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"

>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786

But when the key doesn't exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None) . Both are at least three times faster than del in a try / except statement:

>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
...     del d['missing key']
... except KeyError:
...     pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133

If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:

myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}

And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:

map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}

or in python3 , you must use a list comprehension instead:

[myDict.pop(x, None) for x in ['a', 'c', 'e']]

It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.

You can use a dictionary comprehension to create a new dictionary with that key removed:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

使用“del”关键字:

del dict[key]

We can delete a key from a Python dictionary by the some of the following approaches.

Using the del keyword; it's almost the same approach like you did though -

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

Or

We can do like the following:

But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict .

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}

If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict . Again if we try to print myDict , then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

var = {key:value for key, value in myDict.items() if key != 'one'}

Now if we try to print it, then it'll follow the parent order:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

Or

Using the pop() method.

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}

The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

Fork this gist for future reference, if you find this useful.

You can use exception handling if you want to be very verbose:

try: 
    del dict[key]

except KeyError: pass

This is slower, however, than the pop() method, if the key doesn't exist.

my_dict.pop('key', None)

It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.

The fastest approach is this:

if 'key' in dict: 
    del myDict['key']

But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.

just create a copy of your dictionary.

newMy_dict = my_dict.copy()
if 'key' in newMy_dict :
    del newMy_dict['key']

This way, you can control exception.

Another way is by using items() + dict comprehension.

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don't wish to include.

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}

# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}

# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))

Output:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

Dictionary data type has a method called dict_name.pop(item) and this can be used to delete a key:value pair from a dictionary.

a={9:4,2:3,4:2,1:3}
a.pop(9)
print(a)

This will give the output as:

{2: 3, 4: 2, 1: 3}

This way you can delete an item from a dictionary in one line.

I prefer the immutable version

foo = {
    1:1,
    2:2,
    3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
    return {
        k:v
        for k,v in dct.items() if k not in keyIter
    }

>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}

Single filter on key

  • return "key" and remove it from my_dict if "key" exists in my_dict
  • return None if "key" doesn't exist in my_dict

this will change my_dict in place (mutable)

my_dict.pop('key', None)

Multiple filters on keys

generate a new dict (immutable)

dic1 = {
    "x":1,
    "y": 2,
    "z": 3
}

def func1(item):
    return  item[0]!= "x" and item[0] != "y"

print(
    dict(
        filter(
            lambda item: item[0] != "x" and item[0] != "y", 
            dic1.items()
            )
    )
)

Try this

if key in data:
   del data[key]

You could also use filter with lambda :

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> dict(filter(lambda x: x[0] != 'a', d.items()))
{'b': 2, 'c': 3}
>>>

I'd recommend you to use pop(). This method can also be used to remove items from a list at a particular index value. Take a look below:

my_dict.pop('key', None)

but if the mentioned array is not a dictionary, you'll get TypeError. Hence, you can try 'del' either.

The Python del statement deletes an object. Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword.

The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary. Take a look below:

if key in data:
   del data[key]

There are two differences between pop() and del.

First, the pop() method returns the value of the key removed from a dictionary whereas del does not return any value.

Second, the del keyword returns a KeyError if a key is not in a dictionary. On the other hand, the pop() method only returns a KeyError if you do not specify a second parameter. The second parameter is the default value to be returned if a key is not present in a dictionary.

There are two ways, either you can use pop or directly del. So to use pop you would do

dict.pop("key_name", None) 

Or you can delete it from existence with

del dict["key_name"]

If you want to do that without KeyError , you can declare a temporary class and set it as default value in dict.get, if the value is equal to that class if means that key does not exist

Keys and Dict

a={"Assemblyisscary":3637}
class hello:pass
key1="Assemblyisscary"
key2="Binarylangisnightmare"

Function for deleting

def delkey(dictionary,key):
    class temp:pass
    if (dictionary.get(key,temp)==temp:return False
    else: del dictionary[key];return True

Testing

delete(a,key2)
delete(a,key1)

Output

False
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM