Write a Python program to convert a list into a nested dictionary of keys. Table of ContentsPython dictionary: Exercise-27 with Solution
Sample Solution:-
Python Code:
num_list = [1, 2, 3, 4] new_dict = current = {} for name in num_list: current[name] = {} current = current[name] print(new_dict)Sample Output:
{1: {2: {3: {4: {}}}}}Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
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.
Python: Tips of the Day
Difference In Sets:
To retrieve the difference between two sets:
a = {1,2,3} b = {3,4,5}w c = a.difference(b)- Exercises: Weekly Top 16 Most Popular Topics
- SQL Exercises, Practice, Solution - JOINS
- SQL Exercises, Practice, Solution - SUBQUERIES
- JavaScript basic - Exercises, Practice, Solution
- Java Array: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : Conditional Statement
- HR Database - SORT FILTER: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : String
- Python Data Types: Dictionary - Exercises, Practice, Solution
- Python Programming Puzzles - Exercises, Practice, Solution
- C++ Array: Exercises, Practice, Solution
- JavaScript conditional statements and loops - Exercises, Practice, Solution
- C# Sharp Basic Algorithm: Exercises, Practice, Solution
- Python Lambda - Exercises, Practice, Solution
- Python Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
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. Confusing? Because it is or rather it may quickly become if you stop using common sense when structuring your code using nested lists and dictionaries. We’re going to see a more complex example in a moment. But let’s start simple.
- A Simple Nested List
- A Simple Nested Dictionary
- A More Complex Example
- Operations on Nested Lists and Dictionaries
A Simple Nested List
Lists and dictionaries may be nested. Here’s a simple example of a nested list. Watch how indices are used.
teams = [["Ben", "Bob", "Mike"], ["Ann", "Sue"], ["Ron", "Sarah", "Edwin"]] print(f"In {teams[0][0]}'s team {teams[0][2]} is the oldest.")So, there are two indices, one for each level of nesting. The first index is 0, so it refers to the first element in the outer list, which is the inner list [“Ben”, “Bob”, “Mike”]. The second index refers to the appropriate element inside this list, so the element teams[0][0] is “Ben” and teams[0][2] is “Mike”.
The output is:
In Ben's team Mike is the oldest.A Simple Nested Dictionary
Now a simple nested dictionary:
worker = {"name": {"first": "Jane", "last": "Jackson"}, "address": {"country": "USA", "city": "Denver"}, "age": 57} print(f'Mrs. {worker["name"]["last"]}, aged {worker["age"]}, lives in {worker["address"]["city"]}.')Now there are two keys, again one for each level of nesting. The output is:
Mrs. Jackson, aged 57, lives in Denver.Your Panda3D Magazine
Make Awesome Games and Other 3D Apps
with Panda3D and Blender using Python.
Cool stuff, easy to follow articles.
Get the magazine here (PDF).
A More Complex Example
And now a more complex example: A dictionary that contains simple elements, nested lists and nested dictionaries. Such complicated structures are seldom used, but it’s just to illustrate how the particular elements can be retrieved:
animals = {"species": {"english": "wolf", "latin": "Canis lupus"}, "class": "mammals", "habitats": ["forests", "tundras", "grasslands"], "dimensions": {"body": {"length": 150, "height": 80}, "tail": {"length": 40}}} print("Latin name: " + animals["species"]["latin"]) print("Class: " + animals["class"]) print("Main habitat: " + animals["habitats"][0]) print("Body height: " + str(animals["dimensions"]["body"]["height"]))The output is:
Operations on Nested Lists and Dictionaries
You can perform operations on particular nested lists and dictionaries:
animals = {"species": {"english": "wolf", "latin": "Canis lupus"}, "class": "mammals", "habitats": ["forests", "tundras", "grasslands"], "dimensions": {"body": {"length": 150, "height": 80}, "tail": {"length": 40}}} animals["species"]["french"] = "loup" # add element to dictionary animals["habitats"].append("deserts") # append to list animals["dimensions"]["tail"]["length"] *= 1.5 # augmented assignment print("Names: " + str(animals["species"])) print("Habitats: " + str(animals["habitats"])) print("Tail length: " + str(animals["dimensions"]["tail"]["length"]))The output is:
Names: {'english': 'wolf', 'latin': 'Canis lupus', 'french': 'loup'} Habitats: ['forests', 'tundras', 'grasslands', 'deserts'] Tail length: 60.0Naturally you should avoid overcomplicating things and usually you won’t use lists or dictionaries with so many levels of nesting on a regular basis. I hope, though, that you will be familiar with them if you come across them in code.
Here’s the video version:
Can list be nested in dictionary Python?
You can have dicts inside of a list. The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.
How do you create a nested list in a dictionary?
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.
How do I convert a list to a dictionary in Python?
Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
How do you flatten a dictionary with nested lists and dictionaries in Python?
Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.