Delete item in list in dictionary
In a large dictionary like
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 delete "four" in lists?
EDIT
Is there a way to link fours in lists? As in, eliminating one excludes the others.
Go through the dictionary values and remove 4 from each list:
for a in d.itervalues():
try:
a.remove(4)
except ValueError:
pass
This is not very efficient as removing an item from a list is an O (n) operation. To improve performance, use a different data type (for example, a set).
If the dictionary values are sets, you can do
for a in d.itervalues():
a.discard(4)
It looks like you can use the dictionary "Symmetric", you can 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'm using a set here, but you can do something similar with lists. I wouldn't be surprised if there was some kind of implementation of a "symmetric" dictionary somewhere. Hopefully someone else can point you in the right direction if it exists.
Try to remove all 4s:
for i in d:
while 4 in d[i]:
d[i].remove(4)
I don't know how you can eliminate all 4s at once.
You haven't specified what you want if there are duplicates in the list. The solution I wrote (iterate and then delete ..) doesn't handle duplicates.
>>> d = {'a':[1,2,3,4],'b':[1,2,3,4,5,6],'c':[1,2],'d':[1,4],'e':[1,4,4]}
>>> for l in d.values():
... if 4 in l: l.remove(4)
...
>>> d
{'a': [1, 2, 3], 'c': [1, 2], 'b': [1, 2, 3, 5, 6], 'e': [1, 4], 'd': [1]}
It is not very efficient. if 4 in l
will iterate over the list once and l.remove()
repeat the list again.
If the values contain duplicates of 4, you can use something like this:
d = {}
d['a']=[1,2,3,4]
d['b']=[1,2,3,4,4,5,6]
d['c']=[1,2]
d['d']=[1,4,4,4]
def remove_dup(x,n):
while n in x:
x.remove(n)
return x
for ele in d.itervalues():
try:
remove_dup(ele,4)
except ValueError:
pass
Result:
>>> d
{'a': [1, 2, 3], 'c': [1, 2], 'b': [1, 2, 3, 5, 6], 'd': [1]}