Skip to content
Advertisement

How to remove items from dictionary list, for each value that’s in a list

I am trying to return a list of dictionaries exept for the dictionaries with the same id’s as in game_list_id

This is what i got so far:

list_games = [
    {'id': 10, 'name_game': 'x1'},
    {'id': 20, 'name_game': 'x2'},
    {'id': 30, 'name_game': 'x3'},
    {'id': 40, 'name_game': 'x4'},
    {'id': 50, 'name_game': 'x5'},
    {'id': 60, 'name_game': 'x6'},
    {'id': 70, 'name_game': 'x7'},
    {'id': 80, 'name_game': 'x8'},
    {'id': 90, 'name_game': 'x9'}
]

game_id_list = [10, 30, 40]


def remove_game_id_list(list_games, game_id_list):
    results = []
    for b in game_id_list:
        for i in range(len(list_games)):
            if list_games[i]['id'] != b:
                results.append(list_games[i])

    return results

Advertisement

Answer

You can do that in a single line without a function:

result = [dct for dct in list_games if dct['id'] not in game_id_list]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement