-3

I am working on Python code to remove certain elements in dictionary of lists.

dict ={'s': ['a','b'],'d': ['c','d'],'g': ['e','f']}
values = ['a','c','f']

list2 ={i:j.remove(value) for i,j in dict.items() for k in j for value in values if value in k}

print(list2)

Below code is working giving expected result. I am facing issue with comprehensions(above mentioned code)

for i,j in dict.items():

    for k in j:

        for value in values:

            if value in k:

                j.remove(value)

I am not sure why comprehension is not working. Please help me with efficient way of solving this

Actual Result:

{'s': None, 'd': None, 'g': None}

Expected Result:

{'s': ['b'], 'd': ['d'], 'g': ['e']}
sudhir
  • 219
  • 5
  • 17

3 Answers3

1

Instead of trying to mutate a list mid-iteration, just do membership checks in values by iterating over the members of j:

d ={'s': ['a','b'],'d': ['c','d'],'g': ['e','f']}
values = ['a','c','f']

list2 ={i: [a for a in j if a not in values] for i,j in d.items()}

print(list2)
{'s': ['b'], 'd': ['d'], 'g': ['e']}

As a side-note, I've also removed the dict variable name because it shadows a built-in. This is definitely something to avoid because you can run into some iffy behavior later:


dict = {'a': 1}

d = dict([('b',2), ('c',3)])

TypeError: 'dict' object is not callable
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

I would rename your dict variable to something other than dict:

d = {'s': ['a','b'],'d': ['c','d'],'g': ['e','f']}
values = ['a','c','f']

Just use list comprehension to get the items in each list that aren't in values:

d2 = {k:[i for i in v if i not in values] for k, v in d.items()}
Toby Petty
  • 4,431
  • 1
  • 17
  • 29
0

Using zip():

For understanding:

dict_ ={'s': ['a','b'],'d': ['c','d'],'g': ['e','f']}
values = ['a','c','f']

for (k,v), elem  in zip(dict_.items(), values):
    if elem in v:
        v.remove(elem)
print(dict_)

Using dict-comprehension:

Think of it like:

If element of the list values is not in the list value of key in dict_

print({k:v for (k,v), elem  in zip(dict.items(), values) if elem not in v })

OUTPUT:

{'s': ['b'], 'd': ['d'], 'g': ['e']}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55