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:

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.

Asked by: Julian933 | Posted: 01-10-2021

Answer 1

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.

Answered by: Chelsea888 | Posted: 02-11-2021

Answer 2

a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion)

Answered by: Leonardo463 | Posted: 02-11-2021

Answer 3

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.

Answered by: Oliver925 | Posted: 02-11-2021

Answer 4

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]

Answered by: Connie411 | Posted: 02-11-2021

Similar questions

python - Removing certain Rows from subset of df

I have a pandas dataframe. All the columns right of column#2 may only contain the value 0 or 1. If they contain a value that is NOT 0 or 1, I want to remove that entire row from the dataframe. So I created a subset of the dataframe to only contain columns right of #2 Then I found the indices of the rows that had values other than 0 or 1 and deleted it from the original dataframe. See code below please...

python - Removing SOCKS 4/5 proxy

This question is sort of the opposite of this: How can I use a SOCKS 4/5 proxy with urllib2? Let's say I use a SOCKS 5 proxy using the method accepted in that question. How would I revert it back to no proxy in the same process? i.e start process use proxy .. remove proxy ... ...

removing /n from list of words - python

I have a list as below ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,\nJellicle', 'Cats', 'are', 'rather', 'small;\nJellicle', 'Cats', 'are', 'merry', 'and', 'bright,\nAnd', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.\nJellicle', 'Cats', 'have', 'cheerful', 'faces,\nJellicle', 'Cats', 'have', 'bright', 'black', 'eyes;\nThey', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces\nAnd', 'wait', '...

python - PyQt4: Removing a child from its parent

I've created two uis using the Qt Designer, imported them into my script and set them in the normal way using the setupUi() method. When a button is clicked, and the appropriate method is executed, the new ui is loaded, but all of the widgets and connections from the old one persist. What is the proper way to remove the connections and then delete all of the MainWindow's current children so that only the new ui's w...

python - Removing a prefix from a string

This question already has answers here:

python - Removing a node from a linked list

I would like to create a delete_node function that deletes the node at the location in the list as a count from the first node. So far this is the code I have: class node: def __init__(self): = None # contains the data = None # contains the reference to the next node class linked_list: def __init__(self): self.cur_node = None def add_node(self, data)...

removing file names from a list python

I have all filenames of a directory in a list named files. And I want to filter it so only the files with the .php extension remain. for x in files: if x.find(".php") == -1: files.remove(x) But this seems to skip filenames. What can I do about this?

Python removing items from list

This question already has answers here:

python - Removing image links from a list

one liner for removing blank lines from a file in python?

I'm looking for one liner which will remove all the blank lines from a file in python. python equivalent for --> grep -v '^$' file_name > file_name

python - Why does removing the else slow down my code?

Consider the following functions: def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) They should be equivalent. But there's a performance difference: >>> T(lambda : fact1(1)).repeat(number=10000000) [2.5754408836364746, 2.5710129737854004, 2.5678811073303...

python - Removing specific items from Django's cache?

I'm using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes. If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs. If just the page content changes then I'd like ...

python - Removing the Label From Django's TextArea Widget

How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code: class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea()) This is the HTML that it produces: <label for="...

python - What's the regex for removing dots in acronyms but not in domain names?

I want to remove dots in acronyms but not in domain names in a python string. For example, I want the string 'a.b.c.' to become 'abc' The closest regex I made so far is re.sub('(?:\s|\A).{1}\.',lambda s:[0:2], s) which results to

Removing Array Elements in Python while keeping track of their position

I'v got two numpy arrays. The first array contains some zeros (which are distributed randomly over the length of the array), which I would like to remove. My issue is that I would also like to remove the entries of the second array at the index positions where the first array elements are zero. I only came up with a very cumbersome for-loop. Does anyone have an "elegant" method for doing this? Thx...

regex - Removing empty items from a list (Python)

I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: import re f = open('myfile.txt','r') for line in f.readlines(): if'\bDeposit', line): print line.split(' ') f.close() Thanks

removing pairs of elements from numpy arrays that are NaN (or another value) in Python

I have an array with two columns in numpy. For example: a = array([[1, 5, nan, 6], [10, 6, 6, nan]]) a = transpose(a) I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs that meet a certain condition, in this case if they are NaN. The obvious way I can think of is: new_a = [] for val1, val2 in a: if val2 == nan or va...

Python: Removing spaces from list objects

This question already has answers here:

python - lxml removing <?xml ...> tags when parsing?

I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element &lt;?xml ...&gt;. For example from lxml import etree tree = etree.fromstring('&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;dmodule&gt;test&lt;/dmodule&gt;', etree.XMLParser()) print ...

memory - Help removing items from a text file using python

After implementing some of the solutions in my previous question, I've come up with the following solution: reader = open('C://text.txt') writer = open('C://nona.txt', 'w') counter = 1 names, nums = [], [] row =' ') x = len(row)/2 for (a, b) in [(c, d) for c, d in zip(row[:x], row[x:...

text parsing - Removing values from a list in python

I have a large file of names and values on a single line separated by a space: name1 name2 name3.... Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na. For instance, the final line of name in this file is li...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python