Course
Nested Dictionaries
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Nested Dictionaries
A Python dictionary is said to have a nested structure if value of one or more keys is another dictionary. A nested dictionary is usually employed to store a complex data structure.
The following code snippet represents a nested dictionary:
marklist = { "Mahesh" : {"Phy" : 60, "maths" : 70}, "Madhavi" : {"phy" : 75, "maths" : 68}, "Mitchell" : {"phy" : 67, "maths" : 71}}
Example 1
You can also constitute a for loop to traverse nested dictionary, as in the previous section.
marklist = { "Mahesh" : {"Phy" : 60, "maths" : 70}, "Madhavi" : {"phy" : 75, "maths" : 68}, "Mitchell" : {"phy" : 67, "maths" : 71}}for k,v in marklist.items(): print (k, ":", v)
It will produce the following output
Mahesh : {'Phy': 60, 'maths': 70}Madhavi : {'phy': 75, 'maths': 68}Mitchell : {'phy': 67, 'maths': 71}
Example 2
It is possible to access value from an inner dictionary with
[]
notation or get()
method.print (marklist.get("Madhavi")['maths'])obj=marklist['Mahesh']print (obj.get('Phy'))print (marklist['Mitchell'].get('maths'))
It will produce the following output
686071
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.