简体   繁体   中英

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 ']

I want to remove from results every dictionary that doesn't contain every string in the str list in the text . At the moment I can do it with one condition, for example:

results[:] = [d for d in results if lst[0] in d['text']]

But this wouldn't check if ' 4 ' is in text too.

Simply use all to test if all the items in the list are in a dictionary value and use that in the filter of your list comprehension:

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}]

You could use an all in the condition of your comprehension:

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'}]

You could also use set.issubset and str.split instead:

strs = {'5', '4'}  # this is a set!

[dct for dct in results if strs.issubset(dct['text'].split())]

This will check if your ['text'] splitted at whitespaces contains all the characters in strs . Depending on the length of the text and the number of items in strs this could be faster than the all -approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM