Python: Convert a list into a nested dictionary of keys

Python dictionary: Exercise-27 with Solution

Write a Python program to convert a list into a nested dictionary of keys.

Sample Solution:

Python Code:

# Create a list 'num_list' containing numbers.
num_list = [1, 2, 3, 4]

# Create an empty dictionary 'new_dict' and initialize 'current' to reference the same dictionary.
new_dict = current = {}

# Iterate through the numbers in 'num_list' using a for loop.
for name in num_list:
    # Create a nested empty dictionary under the 'current' dictionary with the current 'name' as the key.
    current[name] = {}
    # Update the 'current' reference to point to the newly created nested dictionary.
    current = current[name]

# Print the 'new_dict' dictionary, which is a nested structure with empty dictionaries.

Sample Output:

{1: {2: {3: {4: {}}}}}

Python Code Editor:

Previous: Write a Python program to count the values associated with key in a dictionary.
Next: Write a Python program to sort a list alphabetically in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.