1

I have a list with dictionaries:

list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 2, "id": 13}, {"nbr": 3, "id": 15}, ...]

I have a list that contains all the id:s I want to remove from the list with dictionaries:

ids = [11, 15, ...]

How can I do this effectively? I saw this answer here, however it does not cover if I need to iterate through the ids list.

w1cked
  • 35
  • 8
  • Do you understand the code in that answer? Do you understand, in particular, how it is testing the id values? Can you think of a way to rewrite the `id` test to check whether the `id` is `in` your `ids` list (hint, hint)? – Karl Knechtel Jul 08 '21 at 07:24
  • Sort of @KarlKnechtel. But my issue is that I need to iterate the ```ids``` list at the same time I'm iterating through the ```list_with_dicts```. No idea how to do that. – w1cked Jul 08 '21 at 07:27
  • You don't iterate over the ids, you check whether the "id" is in the ids using `d["id"] in ids` – mcsoini Jul 08 '21 at 07:31
  • Does this answer your question? [Remove dictionary from list](https://stackoverflow.com/questions/1235618/remove-dictionary-from-list) – cigien Jul 08 '21 at 23:45

1 Answers1

0

You don't have to iterate over the ids list, at least not explicitly. Iterate over the dictionaries list and check if the id value is in the ids list using in. If you itreate over a copy of the list you can use remove(dict) to remove the dictionary from the list

list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 3, "id": 15}, {"nbr": 2, "id": 13}]
ids = [11, 15]

for d in list_with_dicts[:]:
    if d['id'] in ids:
        list_with_dicts.remove(d)

print(list_with_dicts) # [{'nbr': 2, 'id': 13}]

If you want to preserve the original list you can build a new one using list comprehensions

new_list_with_dicts = [d for d in list_with_dicts if d['id'] not in ids]
Guy
  • 46,488
  • 10
  • 44
  • 88