code_junkie

Removing a subset of a dict from within a list

Nov 11th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.45 KB | None | 0 0
  1. a = {1:'', 2:'', 3:'', 4:''}
  2. exclusion = [3, 4, 5]
  3.  
  4. # have to build up a new list or the iteration breaks
  5. toRemove = []
  6. for var in a.iterkeys():
  7. if var in exclusion:
  8. toRemove.append(var)
  9.  
  10. for var in toRemove:
  11. del a[var]
  12.  
  13. for key in exclusion:
  14. a.pop(key, None)
  15.  
  16. a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)
  17.  
  18. exclusion = set([3, 4, 5])
  19.  
  20. for key in exclusion.intersection(a):
  21. del a[key]
Add Comment
Please, Sign In to add comment