如何从dict值中删除列表项?

hob*_*bes 4 python dictionary list python-3.x

我知道这对你们大多数人来说都是基本的,但是请耐心等待我,我正试图将蜘蛛网弄脏,并建立肌肉记忆.

我有一个包含主机名密钥和列表值的主机dict.我希望能够从每个值的列表中删除任何fruit_项.

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
Run Code Online (Sandbox Code Playgroud)

我被困在评论区域,我觉得我错过了另一个迭代(某个地方的新列表?),或者我可能不理解如何写回列表值.任何方向都会有所帮助.

the*_*eye 6

从列表中过滤项目的更好方法是使用带有过滤条件的列表理解并创建一个新列表,如下所示.

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()})
Run Code Online (Sandbox Code Playgroud)

产量

{'abc.com': ['veg_carrots'], '123.com': [None], '456.com': None, 'foo.com': ['veg_potatoes']}
Run Code Online (Sandbox Code Playgroud)

在这种特殊情况下,过滤列表的各个值,并使用字典理解创建新的字典对象.