Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a subset of a dict from within a list

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:
        toRemove.append(var)

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.

like image 519
Dan Avatar asked Oct 03 '08 14:10

Dan


People also ask

How do I remove a dictionary from a list?

To remove a dictionary from a list of dictionaries: Use a list comprehension to iterate over the list. Exclude the matching dictionary from the new list. The list comprehension will return a new list that doesn't contain the specified dictionary.

How do I remove something from a nested dictionary python?

In Python, we use “ del “ statement to delete elements from nested dictionary.

How do you strip a dictionary in python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword.


1 Answers

Consider dict.pop:

for key in exclusion:
     a.pop(key, None)

The None keeps pop from raising an exception when key isn't a key.

like image 130
Blair Conrad Avatar answered Sep 28 '22 18:09

Blair Conrad