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 ?
Is there a way to link the fours in the lists? As in, eliminating one eliminates the others.
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
Method 1: Remove a Key from a Dictionary using the del The del keyword can be used to in-place delete the key that is present in the dictionary in Python.
Iterate over the values of the dictionary and remove the 4 from every list:
for a in d.values():
try:
a.remove(4)
except ValueError:
pass
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
for a in d.values():
a.discard(4)
It seems like you might benefit from making your dictionary "Symmetric", you could do something like this:
def make_symmetric(D):
for key, value in D.items():
for v in value:
D.setdefault(v, set()).add(key)
def add(D, a, b):
D.setdefault(a, set()).add(b)
D.setdefault(b, set()).add(a)
def remove(D, a):
values = D.pop(a)
for v in values:
D[v].remove(a)
And use it something like this:
>>> d = {'a': set([1, 2, 3, 4]),
'b': set([1, 2, 3, 4, 5, 6]),
'c': set([1, 2]),
'd': set([1, 4])}
>>> make_symmetric(d)
>>> d
{1: set(['a', 'c', 'b', 'd']),
2: set(['a', 'c', 'b']),
3: set(['a', 'b']),
4: set(['a', 'b', 'd']),
5: set(['b']),
6: set(['b']),
'a': set([1, 2, 3, 4]),
'b': set([1, 2, 3, 4, 5, 6]),
'c': set([1, 2]),
'd': set([1, 4])}
>>> remove(d, 4)
>>> d
{1: set(['a', 'c', 'b', 'd']),
2: set(['a', 'c', 'b']),
3: set(['a', 'b']),
5: set(['b']),
6: set(['b']),
'a': set([1, 2, 3]),
'b': set([1, 2, 3, 5, 6]),
'c': set([1, 2]),
'd': set([1])}
>>> add(d, 'd', 4)
>>> d
{1: set(['a', 'c', 'b', 'd']),
2: set(['a', 'c', 'b']),
3: set(['a', 'b']),
4: set(['d']),
5: set(['b']),
6: set(['b']),
'a': set([1, 2, 3]),
'b': set([1, 2, 3, 5, 6]),
'c': set([1, 2]),
'd': set([1, 4])}
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.
Try this to remove all 4s:
for i in d:
while 4 in d[i]:
d[i].remove(4)
I don't know a way that you can eliminate all 4s at once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With