Python: Convert more than one list to nested dictionary
Write a Python program to convert more than one list to a nested dictionary.
Visual Presentation:

Sample Solution:
Python Code:
# Define a function 'nested_dictionary' that takes three lists as input and creates a nested dictionary structure.
def nested_dictionary(l1, l2, l3):
# Use a list comprehension to create a list of dictionaries, each containing nested dictionaries.
# The elements of the input lists 'l1', 'l2', and 'l3' are used to create these nested dictionaries.
result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)]
return result
# Create three lists, 'student_id', 'student_name', and 'student_grade'.
student_id = ["S001", "S002", "S003", "S004"]
student_name = ["Adina Park", "Leyton Marsh", "Duncan Boyle", "Saim Richards"]
student_grade = [85, 98, 89, 92]
# Print a message indicating the start of the code section and the original lists.
print("Original strings:")
print(student_id)
print(student_name)
print(student_grade)
# Print a message indicating the intention to create a nested dictionary.
print("\nNested dictionary:")
# Call the 'nested_dictionary' function and create a nested dictionary from the three input lists.
# Assign the result to the variable 'ch', which is not used further.
ch = 'a'
print(nested_dictionary(student_id, student_name, student_grade))
Sample Output:
Original strings: ['S001', 'S002', 'S003', 'S004'] ['Adina Park', 'Leyton Marsh', 'Duncan Boyle', 'Saim Richards'] [85, 98, 89, 92] Nested dictionary: [{'S001': {'Adina Park': 85}}, {'S002': {'Leyton Marsh': 98}}, {'S003': {'Duncan Boyle': 89}}, {'S004': {'Saim Richards': 92}}]
Flowchart:

Python Code Editor:
Previous: Write a Python program to filter a dictionary based on values.
Next: Write a Python program to filter the height and width of students, which are stored in a dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics