Write a Python program to Initialize dictionary with default values


The program creates a dictionary with keys taken from a list of strings and values taken from a dictionary.

  • The list stu contains the names of four students: "Siva", "Sam", "Ram", and "Pooja". The dictionary defaults contains two key-value pairs: "designation" with value "Student" and "Department" with value "BCA".
  • The fromkeys method of the dict class is then used to create a new dictionary with the keys from the list stu and the values from the dictionary defaults. The resulting dictionary is stored in the variable "result" and printed using the print function.

Source Code

stu = ["Siva", "Sam", "Ram", "Pooja"]
defaults = {"designation": "Student", "Department": "BCA"}
 
result = dict.fromkeys(stu, defaults)
print(result)
 
# Individual data
print("\nSiva :",result["Siva"])
print("\nSam :",result["Sam"])
print("\nRam :",result["Ram"])
print("\nPooja :",result["Pooja"])

Output

{'Siva': {'designation': 'Student', 'Department': 'BCA'}, 'Sam': {'designation': 'Student', 'Department': 'BCA'}, 'Ram': {'designation': 'Student', 'Department': 'BCA'}, 'Pooja': {'designation': 'Student', 'Department': 'BCA'}}

Siva : {'designation': 'Student', 'Department': 'BCA'}

Sam : {'designation': 'Student', 'Department': 'BCA'}

Ram : {'designation': 'Student', 'Department': 'BCA'}

Pooja : {'designation': 'Student', 'Department': 'BCA'}