DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

Python Exercise 8: generate a dictionary from different source

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"]
Enter fullscreen mode Exit fullscreen mode
  • Expected output:
{'name': 'Kelly', 'salary': 8000}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Credit

Top comments (0)

DEV runs on 100% open source code known as Forem.

Β 
Contribute to the codebase or host your own.
Β 
Check these out! πŸ‘‡