In a big dictionary, similar to
d = {}
d['a']=[1,2,3,4]
d['b']=[1,2,3,4,5,6]
d['c']=[1,2]
d['d']=[1,4]
how can I quickly remove the 'four' in the lists ?
EDIT
Is there a way to link the fours in the lists? As in, eliminating one eliminates the others.
You didn't mention what you want to happen if there are duplicates in your list. The solution I've written (iterate and then remove..) doesn't handle duplicates.
This isn't very efficient though. The
if 4 in l
will iterate the list once, and thel.remove()
will iterate the list again.It seems like you might benefit from making your dictionary "Symmetric", you could do something like this:
And use it something like this:
I use sets here, but you could do something similar with lists. I wouldn't be surprised if there was already some implementation of a "symmetric" dictionary somewhere. Hopefully someone else can point you in the right direction if it exists.
If values contain duplicates of 4, you could use something like this:
Result:
Iterate over the values of the dictionary and remove the 4 from every list:
This is not really efficient, since removing an element from a list is an O(n) operation. Use a different data type (e.g. a set) for better performance.
If the dictionary values are sets, you can do
Try this to remove all 4s:
I don't know a way that you can eliminate all 4s at once.