简体   繁体   中英

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!

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]}

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()}

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 0 s 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()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM