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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With