Given a list of strings, remove an item from list of dicts based on its value
I have the following list of dicts:
money_line = [
{
"id": 1,
"book": "SPORT_888"
},
{
"id": 2,
"book": "WYNN"
},
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
},
{
"id": 6,
"book": "WYNN_NY"
}
]
And the following list of strings:
list_to_remove = ["SPORT_888", "WYNN", "MGM"]
As you can see, in the dict values I have a suffix on "WYNN_NY" items. I need to remove from money_line all items that are in list_to_remove, ignoring the suffix.
Already tried:
live_money_line = [i for i in money_line if i['book'].rsplit('_', 1)[0] not in list_to_remove]
But that would remove "888" "SPORT_888", and that's not the result I need.
Also tried:
for code in list_to_remove:
for item in money_line:
if code in item['book']:
money_line.remove(item)
But for some reason it's not working properly. It keeps wrong items on the money_line list.
Am I missing something in this for loop, or is there a better way to make this work?
Desired result:
money_line = [
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
}
]
You can use startswith()
and any()
together to filter out the dictionaries you don't want:
money_line = [
{
"id": 1,
"book": "SPORT_888"
},
{
"id": 2,
"book": "WYNN"
},
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
},
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
},
{
"id": 6,
"book": "WYNN_NY"
}
]
list_to_remove = ["SPORT_888", "WYNN", "MGM"]
[d for d in money_line if not any(d['book'].startswith(token) for token in list_to_remove)]
Which results in:
[{'id': 3, 'book': 'BET_RIVERS_VA'},
{'id': 4, 'book': 'WILLIAM_HILL'},
{'id': 5, 'book': 'SUGAR_HOUSE_NJ'}]