Given:
sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } # Keys to remove keys = ["name", "salary"]
Expected output:
{'city': 'New york', 'age': 25}
Hint:
To achieve the above result, we can use the dictionary comprehension or the pop() method of a dictionary.
pop()
Solution1:Using the pop() method and loop
sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } # Keys to remove keys = ["name", "salary"] for k in keys: sample_dict.pop(k) print(sample_dict)
Solution2:Dictionary Comprehension
sample_dict = { "name": "Kelly", "age": 25, "salary": 8000, "city": "New york" } # Keys to remove keys = ["name", "salary"] sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys} print(sample_dict)
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Hint:
To achieve the above result, we can use the dictionary comprehension or the
pop()
method of a dictionary.Solution1:Using the
pop()
method and loopSolution2:Dictionary Comprehension
need an explanation for this answer? contact us directly to get an explanation for this answer