1

I'm trying to complete the following short exercise: Iterate a given list and Check if a given element already exists in a dictionary as a key’s value if not delete it from the list.

My solutions seem to work and remove all items from the list, which doesn't exist in the dictionary as values, beside one value... 95. How can it be?

When I'm doing debug, during the iteration of the loop, it seems that Python skips that value (95):

rollNumber = [47, 64, 69, 37, 76, 83, 95, 96, 97]
sampleDict = {"Jhon": 47, "Emma": 69, "Kelly": 76, "Jason": 97}

for current_item in rollNumber:
    if not current_item in sampleDict.values():
        rollNumber.remove(current_item)

print(rollNumber)

Actual results:

[47, 69, 76, 95, 97]

Expected results:

[47, 69, 76, 97]
Dmitriy Kisil
  • 2,858
  • 2
  • 16
  • 35
Tal
  • 11
  • 2

1 Answers1

0

try this

rollNumber = [47, 64, 69, 37, 76, 83, 95, 96, 97]
sampleDict = {"Jhon": 47, "Emma": 69, "Kelly": 76, "Jason": 97}

rollNumber = [i for i in rollNumber if i in sampleDict.values()]

print(rollNumber)

result: [47, 69, 76, 97]

LinPy
  • 16,987
  • 4
  • 43
  • 57