How to remove a key from a Python dictionary

0 votes

When deleting a key from a dictionary, I use:

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

Is there a one line way of doing this?

Apr 15, 2020 in Python by kartik
• 37,530 points
247 views

1 answer to this question.

0 votes

Hello,

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.

Hope this work!!

Thank You!!

answered Apr 15, 2020 by Niroj
• 82,820 points

Related Questions In Python

0 votes
1 answer

How to Remove specific characters from a string in Python?

Strings in Python are immutable (can't be changed). Because ...READ MORE

answered Jan 5 in Python by Gitika
• 65,950 points
129 views
0 votes
3 answers

How to get the return value from a thread using python?

FWIW, the multiprocessing module has a nice interface for ...READ MORE

answered Dec 15, 2020 in Python by Roshni
• 10,480 points
71,926 views
0 votes
1 answer

How to correctly return an a dictionary as an output in zappier code using python?

David here, from the Zapier Platform team. ...READ MORE

answered Dec 3, 2018 in Python by charlie_brown
• 7,780 points
631 views
0 votes
1 answer

How to use read a WSDL file from the file system using Python suds?

Hi, good question. It is a very simple ...READ MORE

answered Jan 21, 2019 in Python by Nymeria
• 3,520 points
4,693 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,364 views
0 votes
0 answers
0 votes
1 answer

How to delete items from a dictionary while iterating over it?

Hii Kartik, You could do it in two ...READ MORE

answered Apr 30, 2020 in Python by Niroj
• 82,820 points
839 views
0 votes
1 answer

How to execute a Python script from the Django shell?

Hello @kartik, The << part is wrong, use < instead: $ ./manage.py shell ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,820 points
5,789 views