Question
- Write a Python program to create a new dictionary by extracting the mentioned keys from the below dictionary.
- **Given
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# Keys to extract
keys = ["name", "salary"]
{'name': 'Kelly', 'salary': 8000}
My attempt
Decomposition of question
- initialise an empty dictionary: new_dict
- iterate over the list named keys
- for each key in keys
- check whether the key is appear in the sample_dict
- if the key is in the sample_dict, add the items in the sample_dict to the new_dict
- print out the new list
def get_items_from_dict(keys, dictionary):
new_dict = {}
for key in keys:
if key in dictionary:
new_dict.update({key: dictionary.get(key)})
print(new_dict)
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# Keys to extract
keys = ["name", "salary"]
get_items_from_dict(keys, sample_dict)
Recommend solution
- use 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)
Credit
Top comments (0)