Reputation: 1174
I have dictionary in python with key as 'string' and value as list of integers. Iterating the dict with key and value and if delete the value in the list if it does not meet some conditions. Iteration does not properly.
For example,
my_dict = {"emp_id":[100,200]}
for emp,ids in my_dict.iteritems():
print "Emp :",emp
for id in ids:
print "Id :",id
if not id > 1000:
my_dict.get(emp).remove(id)
continue
Output :
Emp : emp_id
Id : 100
It does not iterate the second value (200) in the list. Not sure what could be problem. Is it due the removal of value in the dict.
How to resolve this. Do we need to do copy to another object and remove from it.
Upvotes: 0
Views: 290
Reputation: 6111
you should not remove element during iteration
my_dict={'emp_id': [100, 200, 10000]}
new_dict={ emp:[ele for ele in ids if ele <= 1000] for emp,ids in my_dict.iteritems() }
{'emp_id': [100, 200]}
Upvotes: 2
Reputation: 530990
You cannot reliably modify a list over which you are iterating. Simply filter the list, then replace it with the filtered copy.
for emp, ids in mydict.iteritems():
print "Emp:", emp
new_ids = []
for id in ids:
print "Id", id
if id > 1000:
new_ids.append(id)
my_dict[emp] = new_ids
If you aren't printing each id as you see it, you can replace the inner loop with a single call to filter
:
for emp, ids in my_dict.iteritems():
my_dict[emp] = [id for id in ids if id > 1000]
# my_dict[emp] = filter(lambda x: x > 1000, ids)
You could even rebuild the entire dict
from scratch:
my_dict = {emp: [id for id in ids if id > 1000] for emp, ids in my_dict.iteritems()}
Upvotes: 2
Reputation: 509
It's not good to modify my_dict during iteration.
If you want to just print: not (id > 1000), then remove my_dict.get(emp).remove(id).
Otherwise, remove first then print.
Upvotes: -1