Q:

Iterate a given list and check if a given element exists as a key’s value in a dictionary. If not, delete it from the list using python programming

belongs to collection: Python Data Structure Exercises

0

Iterate a given list and check if a given element exists as a key’s value in a dictionary. If not, delete it from the list

Given:

roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}

Expected Outcome:

After removing unwanted elements from list [47, 69, 76, 97]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Solution:

roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {'Jhon': 47, 'Emma': 69, 'Kelly': 76, 'Jason': 97}

print("List:", roll_number)
print("Dictionary:", sample_dict)

# create new list
roll_number[:] = [item for item in roll_number if item in sample_dict.values()]
print("after removing unwanted elements from list:", roll_number)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Get all values from the dictionary and add them to... >>
<< Checks if one set is a subset or superset of anoth...