Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a list item from a dict value?

I have a host dict that contains a hostname key, and list values. I would like to be able to remove any item of fruit_ 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'm stuck around the commented area, I feel like I'm missing another iteration (new list somewhere?), or maybe I'm not understanding how to write the list value back. Any direction would be helpful.

like image 828
hobbes Avatar asked Mar 07 '23 02:03

hobbes


1 Answers

A better way to filter items from a list is to use list comprehension with a filtering condition and create a new list, like this.

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

In this particular case, individual values of the lists are filtered and a new dictionary object is created with dictionary comprehension.

like image 152
thefourtheye Avatar answered Mar 20 '23 23:03

thefourtheye