Iterate a given list and check if a given element exists as a key

Python Python Dictionary (Article) Python Dictionary (Program)

619

Given Input:

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

Expected Output:

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

Program:

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)

Output:

List: [47, 64, 69, 37, 76, 83, 95, 97]
Dictionary: {'Jhon': 47, 'Emma': 69, 'Kelly': 76, 'Jason': 97}
after removing unwanted elements from list: [47, 69, 76, 97]

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.