Reputation:
I have a list val
val = ['ed2', 'll', 'mal', 'DC', 'sp3', 'oo']
and a dictionary d
d = {'A': ['2500ed2', '545ll', 'fine', '340DC'], 'B': ['Q5mal', 'fern','2DC', '2mal', 'fist', 'Q12mal']}
I would like to skip any strings ending with any of the values contained in val
e.g. 2500ed2
would be skipped since it ends with ed2
but fine
would be kept in the final dictionary because it doesn't end in any of the values in val
. I would like my final output to be
d = {'A': ['fine'],'B': ['fern','fist']}
I have tried the following but this doesn't quite work
d = {}
for k, v in d.items():
d[k] = [n for n in v if n not in val]
How do I change my loop to get my desired output?
Upvotes: 0
Views: 59
Reputation: 2783
You can a list comprehension, with endswith()
:
result = {}
for key, value in d.items():
result[key] = [s for s in value if not any(s.endswith(v) for v in val)]
Per @ShadowRanger, you can improve this by converting val
to a tuple before entering the loop. This means you don't need a generator or list comprehension to iterate over val
, as endswith()
can take a tuple as its argument:
result = {}
val = tuple(val)
for key, value in d.items():
result[key] = [s for s in value if not s.endswith(val)]
Upvotes: 1
Reputation: 6542
You could use endswith()
:
d = { k:[ev for ev in v if not any(ev.endswith(x) for x in val)]
for k,v in d.items() }
Upvotes: 1