Working with Nested Dictionaries in Python: Multilevel Key-Value Structures

thumb_up 1  ·  sell Python nested dictionaries, Managing multilevel key-value pairs in Python, Handling nested dictionaries in Python

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 −

68
60
71

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back