How to remove list item from dict value?

I know that this will be the main one for most of you, but bear with me, I'm trying to burn the web and build muscle memory.

I have a pointer to a host containing a host key and a list. I would like to be able to remove any fruit_ element from the list of each value.

host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': None, 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

for v in host.values():
  if v is not None:
    for x in v:
      try:
        # creating my filter
        if x.startswith('fruit_'):
        # if x finds my search, get, or remove from list value
         host(or host.value()?).get/remove(x)# this is where i'm stuck
        print(hr.values(#call position here?)) # prove it
      except:
        pass

I am stuck around the comment area, I feel like I am missing another iteration (a new list somewhere?), Or maybe I don’t understand how to write the value of the list back. Any direction would be helpful.

+4
source share
3 answers

The best way to filter items from a list is to use a list comprehension with a filter condition and create a new list, for example.

host = {
    'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'],
    '123.com': [None],
    '456.com': None,
    'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}


def reconstruct_list(vs):
    return vs if vs is None else [
        v for v in vs if v is None or not v.startswith('fruit_')
    ]


print({k: reconstruct_list(vs) for k, vs in host.items()})

Output

{'abc.com': ['veg_carrots'], '123.com': [None], '456.com': None, 'foo.com': ['veg_potatoes']}

.

+6

dict:

>>> host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': [None] , 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

>>> {k: [x for x in v if not str(x).startswith('fruit_') or not x] for k, v in host.items()}
{'abc.com': ['veg_carrots'], '123.com': [None], 'foo.com': ['veg_potatoes']}

, '123.com' None , :

>>> host = { 
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], 
  '123.com': None , 
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}

>>> {k: v if not v else [x for x in v if not x.startswith('fruit_')] for k, v in host.items()}
{'abc.com': ['veg_carrots'], '123.com': None, 'foo.com': ['veg_potatoes']}
+1

You can try something like this:

host = {
  'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'],
  '123.com': None,
  'foo.com': ['fruit_tomatoes', 'veg_potatoes']
}


print({i:[k for k in j if not k.startswith('fruit_')] if j!=None  else None for i,j in host.items() })

But if there is no None, you can try this interesting approach:

print(dict(map(lambda z,y:(z,list(filter(lambda x:not x.startswith('fruit_'),host[y]))),host,host)))
0
source

Source: https://habr.com/ru/post/1692561/


All Articles