![](/img/trans.png)
[英]How to remove the entire dictionary from a list of dictionaries if a specific key is empty?
[英]Python - Remove dictionary from list of dictionaries if list of strings not in dictionary key
results = [
{'id': 1, 'text': 'String 55 - 1' },
{'id': 2, 'text': 'String 3 - 2' },
{'id': 3, 'text': 'String 5 - 4 - 1'}]
str = [' 5 ', ' 4 ']
我想从results
删除每个不包含text
str
列表中每个字符串的字典。 目前,我可以使用一种条件进行操作,例如:
results[:] = [d for d in results if lst[0] in d['text']]
但这也不会检查' 4 '
是否也在文本中。
只需使用all
来测试列表中的所有项目是否都在字典值中,然后在列表理解的过滤器中使用它:
lst = [' 5 ', ' 4 ']
results[:] = [d for d in results if all(i in d['text'] for i in lst)]
print(results)
# [{'text': 'String 5 - 4 - 1', 'id': 3}]
您可以在理解的情况下使用all
:
results = [
{'id': 1, 'text': 'String 55 - 1' },
{'id': 2, 'text': 'String 3 - 2' },
{'id': 3, 'text': 'String 5 - 4 - 1'}]
strs = [' 5 ', ' 4 '] # you shouldn't name it "str" because that's a builtin function
>>> [dct for dct in results if all(substr in dct['text'] for substr in strs)]
[{'id': 3, 'text': 'String 5 - 4 - 1'}]
您还可以使用set.issubset
和str.split
代替:
strs = {'5', '4'} # this is a set!
[dct for dct in results if strs.issubset(dct['text'].split())]
这将检查在空格处分割的['text']
包含strs
中的所有字符。 根据长度text
和项目的数量strs
,这可能是比快all
-approach。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.