w3resource

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.
print(new_dict)
 

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-27.php