A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Delete a list of keys from a dictionary using python programming
Q:

Delete a list of keys from a dictionary using python programming

0

Delete a list of keys from a dictionary

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}

All Answers

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

Hint:

  • Iterate the mentioned keys using a loop
  • Next, check if the current key is present in the dictionary, if it is present, remove it from the dictionary

To achieve the above result, we can use the dictionary comprehension or the pop() method of a dictionary.

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)

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now