保留字典中不在列表中的值 [英] keep values from dictionary that are not in list

查看:88
本文介绍了保留字典中不在列表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表val

val = ['ed2', 'll', 'mal', 'DC', 'sp3', 'oo']

和字典d

d = {'A': ['2500ed2', '545ll', 'fine', '340DC'], 'B': ['Q5mal', 'fern','2DC', '2mal', 'fist', 'Q12mal']}

我想跳过任何以val中包含的任何值结尾的字符串,例如2500ed2将被跳过,因为它以ed2结尾,但是fine将保留在最终字典中,因为它没有以val中的任何值结尾.我希望我的最终输出是

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?

推荐答案

您可以使用endswith():

d = { k:[ev for ev in v if not any(ev.endswith(x) for x in val)]
      for k,v in d.items() }

这篇关于保留字典中不在列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆