Removing a subset of a dict from within a list

By : Dan

This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:

a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]

# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
    if var in exclusion:

for var in toRemove:
    del a[var]

This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.

This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.

By : Dan


You could change your exclusion list to a set, then just use intersection to get the overlap.

exclusion = set([3, 4, 5])

for key in exclusion.intersection(a):
    del a[key]
By : Brian

Why not just use the keys method, instead of iterkeys? That way you can do it in one loop because it returns a list, not an iterator.

a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)
By : Dave Webb

This video can help you solving your question :)
By: admin