Nikki
Nikki

Reputation: 363

Deleting items witht the same index from multiple lists inside a dictionary

I have a dictionary consisting of lists, for example

mydict={}

mydict['a']=[1,0,0,0,1,1,1,1,1,0,0]

mydict['b']=[2,4,5,6,8,7,5,4,5,6,7]

mydict['c']=[4,5,6,4,6,8,4,3,5,8,7]

Now say that if in 'a' the value is 0, I want to delete the item with that index from every list in the libraby. So for the first 0 that would be removing 0 from 'a', 4 from 'b' and 5 from 'c', for the second 0: 0 from 'a', 5 from 'b' and 6 from 'c' etc.

I've been trying to do this in many different ways, but I just do not manage to find the right way. Does anyone know how to do this? Would be great!

Upvotes: 0

Views: 51

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121774

Simple loop approach:

index = mydict['a'].index(0)

for value in mydict.values():
    del value[index]

but that removes only one item.

For multiple items:

indices = {i for i, v in enumerate(mydict['a']) if v == 0}
mydict = {k: [x for i, x in enumerate(v) if i not in indices]
          for k, v in mydict.items()}

Use dictionary.iteritems() when using Python 2.

Using itertools.compress() supporting arbitrary values:

from itertools import compress

value_to_remove = 0
mask = [v != value_to_remove for v in mydict['a']]
value_to_remove = 0
mydict = {k: list(compress(v, mask)) for k, v in mydict.items()}

Upvotes: 0

BartoszKP
BartoszKP

Reputation: 35891

Here is one possible solution:

mydict={}

mydict['a']=[1,0,0,0,1,1,1,1,1,0,0]

mydict['b']=[2,4,5,6,8,7,5,4,5,6,7]

mydict['c']=[4,5,6,4,6,8,4,3,5,8,7]

toRemove = [i for i,x in enumerate(mydict['a']) if x == 0]

for key in mydict.keys():
    mydict[key] = [x for i,x in enumerate(mydict[key]) if i not in toRemove]

print(mydict)

>>>{'a': [1, 1, 1, 1, 1, 1], 'c': [4, 6, 8, 4, 3, 5], 'b': [2, 8, 7, 5, 4, 5]}

Assuming you also want to remove 0s from the 'a' list. If not adding a simple condition will help.

Alternatively, even more concise but less readable approach:

mydict = {key:[x for i,x in enumerate(value) if i not in indices] 
          for key, value in mydict.iteritems()}

Upvotes: 0

falsetru
falsetru

Reputation: 369064

Using itertools.compress:

>>> import itertools
>>>
>>> mydict={}
>>> mydict['a']=[1,0,0,0,1,1,1,1,1,0,0]
>>> mydict['b']=[2,4,5,6,8,7,5,4,5,6,7]
>>> mydict['c']=[4,5,6,4,6,8,4,3,5,8,7]
>>> #            ^       ^ ^ ^ ^ ^
>>> mask = mydict['a']
>>> for key, value in mydict.items():
...     mydict[key] = list(itertools.compress(value, mask))
...
>>> mydict
{'a': [1, 1, 1, 1, 1, 1], 'c': [4, 6, 8, 4, 3, 5], 'b': [2, 8, 7, 5, 4, 5]}

Upvotes: 4

Related Questions