DEV Community

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

4 3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more