How to Create a Nested Dictionary from User Input in Python?

Estimated read time 2 min read

You can create a nested dictionary from user input in Python by using a loop to ask the user for keys and values and creating the nested dictionaries on the fly. Here’s an example:

nested_dict = {}
current_dict = nested_dict

while True:
    key = input("Enter key (blank to stop adding): ")
    if not key:
        break
    
    value = input("Enter value: ")
    
    # create nested dictionary
    current_dict[key] = {}
    current_dict = current_dict[key]
    
    # add value to final dictionary
    current_dict["value"] = value
    
print(nested_dict)

In this example, we start with an empty dictionary called nested_dict. We also create a variable called current_dict that we use to keep track of the current dictionary we’re adding keys and values to.

We then enter a loop that continues until the user enters a blank key. Inside the loop, we first ask the user for a key and value. We then create a new nested dictionary at the current level by setting the value of the current key to a new empty dictionary. We then update current_dict to be this new dictionary, so that the next key and value will be added to the nested dictionary.

Finally, we add the provided value to the final nested dictionary by setting the value of the “value” key to the provided value.

After the loop, we print out the final nested dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply