Instagram
youtube
Facebook
Twitter

Python Program to Create a Dictionary by Extracting Specific Keys

A Python Program to Create a Dictionary by Extracting Specific Keys?

Code Explanation:

Original Dictionary:
A sample dictionary sample_dict is defined with multiple key-value pairs.

Keys to Extract:
A list keys is created with the keys that need to be extracted from the original dictionary.

Dictionary Comprehension:
A new dictionary new_dict is created using a dictionary comprehension by selecting only those keys which are present in the keys list.

Print Result:
The new dictionary is printed, which contains only the selected key-value pairs.

 

Program:

sample_dict = {

    "name": "John",

    "age": 25,

    "gender": "Male",

    "location": "New York"

}

# Keys to extract

keys = ["name", "age"]

# Create new dictionary with extracted keys

new_dict = {k: sample_dict[k] for k in keys}

print("New dictionary:", new_dict)