How to delete items from a dictionary while iterating over it

0 votes

Is it legitimate to delete items from a dictionary in Python while iterating over it?

For example:

for k, v in mydict.iteritems():
   if k == val:
     del mydict[k]

The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of the one being iterated over.

Is this a good solution? Are there more elegant/efficient ways?

Apr 30, 2020 in Python by kartik
• 37,510 points
2,516 views

1 answer to this question.

0 votes

Hii Kartik,

You could do it in two steps:

remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]

My favorite approach is usually to just make a new dict:

# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)

Thank You!!

answered Apr 30, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to write a python script for downloading a video from YouTube and saving it to a directory?

First download pytube using the following code  pip ...READ MORE

answered Sep 4, 2019 in Python by Neel
• 3,020 points
2,419 views
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 22, 2018 in Python by SDeb
• 13,300 points
4,678 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 58,090 points
1,850 views
0 votes
1 answer

How to Parse values from a JSON file?

import json from pprint import pprint with open('data.json') as ...READ MORE

answered Oct 15, 2018 in Python by Priyaj
• 58,090 points
1,704 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,061 views
0 votes
1 answer
0 votes
1 answer

How to remove a key from a Python dictionary?

Hello, If you need to remove a lot ...READ MORE

answered Apr 15, 2020 in Python by Niroj
• 82,880 points
1,430 views
0 votes
1 answer

How to use a dot “.” to access members of dictionary?

Hello @kartik, If you want to pickle your ...READ MORE

answered Apr 30, 2020 in Python by Niroj
• 82,880 points
2,340 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP