You get an error because your syntax is wrong. The following appends to the list value for the 'Numbers' key:

myDict['Numbers'].append(user_inputs)

You can nest Python objects arbitrarily; your myDict2 syntax is entirely correct. Only the keys need to be immutable (so a tuple vs. a list), but your keys are all strings:

>>> myDict2 = {'Names': [{'first name':[],'Second name':[]}]}
>>> myDict2['Names']
[{'first name': [], 'Second name': []}]
>>> myDict2['Names'][0]
{'first name': [], 'Second name': []}
>>> myDict2['Names'][0]['first name']
[]
Answer from Martijn Pieters on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_nested.asp
Python - Nested Dictionaries
Remove List Duplicates Reverse ... Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... A dictionary can contain dictionaries, this is called nested ......
Discussions

How to create a nested dictionary from a list in Python? - Stack Overflow
I have a list of strings: tree_list = ['Parents', 'Children', 'GrandChildren'] How can i take that list and convert it to a nested dictionary like this? tree_dict = { 'Parents': { 'Ch... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to walk through a nested dictionary with it's keys in a list?
What I would do is make a copy of the dict to a temporary dict and then index it with a for loop: T = D for i in L: T = T[i] Now T will be equal to D['product']['item']['serial_key'] Check out working example: http://codepad.org/64NhJMBS More on reddit.com
๐ŸŒ r/learnpython
24
129
March 9, 2021
python - Nested list to dict - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to Convert Nested List into dictionary in Python where lst[0][0] is the key - Stack Overflow
@mohammed the terms to lookup are "slicing" and "dictionary comprehension" - that'll give you a good starting point. Good luck with Python. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
PacketPushers
packetpushers.net โ€บ home โ€บ how to reference nested python lists & dictionaries
How To Reference Nested Python Lists & Dictionaries
January 26, 2024 - Weโ€™ll walk through lists, dictionaries, and nested combinations of the two using a series of examples. A Python list is a series of objects referenced numerically by position. Lists are delimited by square brackets. List items are separated by commas. ... A Python dictionary (aka dict) is a series of key-value pairs referenced by key name. Dicts are delimited by curly braces. Key-value pairs are separated by commas. A key is separated from its value by a colon. In this example, I split the key-value pairs across lines for readability.
๐ŸŒ
Prospero Coder
prosperocoder.com โ€บ home โ€บ nested list and dictionary basics
Nested List and Dictionary Basics - Prospero Coder
May 1, 2022 - Today weโ€™ll be talking about the nested list and dictionary. Nested lists and dictionaries are often used to better structure your data. Theoretically there are no limits to the depth of nesting and you can have a list inside another list, which is inside yet another list, which itself also is inside another list, etc.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-create-nested-dictionary-using-given-list
Create Nested Dictionary using given List โ€“ Python | GeeksforGeeks
February 4, 2025 - The task of creating a nested dictionary in Python involves pairing the elements of a list with the key-value pairs from a dictionary. Each key from the list will map to a dictionary containing a corresponding key-value pair from the original ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Nesting Dictionaries and Lists in Python - YouTube
Nesting dictionaries and lists within one another is something Python does rather well. Through nesting these dictionaries and list we can make our code more...
Published ย  September 9, 2020
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ dictionary โ€บ python-data-type-dictionary-exercise-27.php
Python: Convert a list into a nested dictionary of keys - w3resource
# 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) ... Write a Python program to recursively convert a list of elements into a nested dictionary, where each element is a key.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ convert-lists-to-nested-dictionary-in-python
Convert Lists to Nested Dictionary in Python
July 17, 2023 - The nested dictionary: {'Letter': {'A': 1}, 'Word': {'Box': 3}, 'Number': {'Integer': 41905}} Recursive functions can handle complex nested structures with arbitrary depth ? def create_nested_dict(lst, depth=0): # Base case: if depth exceeds list length, return empty dict if depth >= len(lst[0]) if lst else True: return {} # Group items by current depth element result = {} for item in lst: if depth < len(item): key = item[depth] if key not in result: result[key] = [] result[key].append(item) # Recursively create nested structure return {key: create_nested_dict(group, depth + 1) for key, group in result.items()} my_list = [['a', 'b', 'c'], ['a', 'b', 'd'], ['x', 'y', 'z']] result = create_nested_dict(my_list) print("List to Nested Dictionary:") print(result)
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ creating-a-nested-dictionary-using-a-given-list-in-python
Python - Nested Dictionaries
We can create a nested dictionary in Python by defining a dictionary where the values of certain keys are themselves dictionaries. This allows for the creation of a hierarchical structure where each key-value pair represents a level of nested ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-lists-to-nested-dictionary
Convert Lists to Nested Dictionary โ€“ Python | GeeksforGeeks
February 12, 2025 - The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary.
๐ŸŒ
Devcamp
bottega.devcamp.com โ€บ full-stack-development-javascript-python โ€บ guide โ€บ guide-lists-nested-dictionaries
Guide to Working with Lists of Nested Dictionaries
So Astro's is the key and then we have a second dictionary nested inside of it here and now let's set up some key-value pairs. I'm going to say Second base is going to be Altuve then shortstop is going to be Correa and let's go with one more third base is going to be Bregman. So that is our nested dictionary. So once again we have teams which is a list.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ convert-nested-dictionary-to-list-python
Convert Nested Dictionary to List in Python - GeeksforGeeks
July 23, 2025 - The lambda function processes each ... the result to a list. For deeply nested dictionaries, recursion can be used to convert all nested structures into lists....
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ nested-dictionary
Python Nested Dictionary (With Examples)
In this article, youโ€™ll learn about nested dictionary in Python. More specifically, youโ€™ll learn to create nested dictionary, access elements, modify them and so on with the help of examples.
๐ŸŒ
Learn By Example
learnbyexample.org โ€บ python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - Here, zip() combines the IDs and EmpInfo lists, creating pairs that dict() then converts into a nested dictionary.
Top answer
1 of 16
343

Use reduce() to traverse the dictionary:

Copyfrom functools import reduce  # forward compatibility for Python 3
import operator

def getFromDict(dataDict, mapList):
    return reduce(operator.getitem, mapList, dataDict)

and reuse getFromDict to find the location to store the value for setInDict():

Copydef setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

All but the last element in mapList is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.

Demo:

Copy>>> getFromDict(dataDict, ["a", "r"])
1
>>> getFromDict(dataDict, ["b", "v", "y"])
2
>>> setInDict(dataDict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(dataDict)
{'a': {'r': 1, 's': 2, 't': 3},
 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}

Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path() and set_by_path():

Copyfrom functools import reduce  # forward compatibility for Python 3
import operator

def get_by_path(root, items):
    """Access a nested object in root by item sequence."""
    return reduce(operator.getitem, items, root)

def set_by_path(root, items, value):
    """Set a value in a nested object in root by item sequence."""
    get_by_path(root, items[:-1])[items[-1]] = value

And for completion's sake, a function to delete a key:

Copydef del_by_path(root, items):
    """Delete a key-value in a nested object in root by item sequence."""
    del get_by_path(root, items[:-1])[items[-1]]
2 of 16
92

It seems more pythonic to use a for loop. See the quote from Whatโ€™s New In Python 3.0.

Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

Copydef nested_get(dic, keys):    
    for key in keys:
        dic = dic[key]
    return dic

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

def nested_del(dic, keys):
    for key in keys[:-1]:
        dic = dic[key]
    del dic[keys[-1]]

Note that the accepted solution doesn't set non-existing nested keys (it raises KeyError). Using the approach above will create non-existing nodes instead.

The code works in both Python 2 and 3.