Create a dictionary by extracting the keys from a given dictionary


The program creates a new dictionary by selecting a subset of key-value pairs from an existing dictionary. The dictionary student contains information about a student, including their name, roll number, marks, and city. The list keys contains a subset of the keys in the student dictionary: "Name", "RollNo", and "Mark".

The program then uses a dictionary comprehension to create a new dictionary n that contains only the key-value pairs from student for which the keys are in the keys list. The dictionary comprehension iterates over the elements in the keys list, and for each element, it adds a key-value pair to the new dictionary n with the key taken from the keys list and the value taken from the student dictionary.

Source Code

student = { 
  "Name": "Tara",
  "RollNo":130046, 
  "Mark": 458, 
  "City": "Chennai" }
 
keys = ["Name", "RollNo", "Mark"]
 
n = {k: student[k] for k in keys}
print(n)

Output


{'Name': 'Tara', 'RollNo': 130046, 'Mark': 458}