0
idlist = ['101', '102']
myd = [
    {'id':'101', 'role': 'tester'},
    {'id':'102', 'role': 'tester'},
    {'id':'103', 'role': 'tester'}
]
  • I have idlist
  • I need to check if a dictionary with the id is present in myd
  • I need to remove the items with matching id

Expected output:

101 and 102 are deleted

[{'id':'103', 'role': 'tester'}]

Code is below

for ids in idlist:
    for each in myd.items():
        if ids == each['id']
             del each

Do I need to do 2 for loop function to resolve this?

2
  • myd is a list so myd.items() won't do anything. You need to break down your problem into steps instead of trying to tackle everything at the same time. Commented Aug 26, 2021 at 15:14
  • The condition being ids['id'] not in idlist. Commented Aug 26, 2021 at 15:14

2 Answers 2

3

You can use a simple comprehension:

s = set(idlist)  # better membership test than list

myd[:] = [d for d in myd if d['id'] not in s]

It is usually better to build a list from scratch than to repeatedly remove elements. The slice assignment myd[:] = ... just makes sure this is a mutation on the existing list object as removing elements would be.

Sign up to request clarification or add additional context in comments.

Comments

2

A single liner:

myd = [x for x in myd if x['id'] not in idlist]

Esentially creates a new list with the values that are not in idlist. You can assign this to myd if you like to overwrite it.

NOTE: This is not deleting from the list but rather replacing the list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.