Next, check if the current key is present in the dictionary, if it is present, add it to the new dictionary
Solution1:Dictionary Comprehension
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york" }
keys = ["name", "salary"]
newDict = {k: sampleDict[k] for k in keys}
print(newDict)
Solution2:Using the update() method and loop
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# keys to extract
keys = ["name", "salary"]
# new dict
res = dict()
for k in keys:
# add current key with its va;ue from sample_dict
res.update({k: sample_dict[k]})
print(res)
Hint:
Solution1:Dictionary Comprehension
Solution2:Using the
need an explanation for this answer? contact us directly to get an explanation for this answerupdate()
method and loop