+91 81900 98289

Nested Dictionaries

This Nested Dictionaries lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A dict value can be another dict. Read the inner value with a second pair of brackets.

get on the outer dict does not search inside. Check each level, or use a default before you index further.

Example 1: Start here

If batch might be missing, read it with get and test the result before the second lookup.

learner = {"name": "Meera", "batch": {"topic": "Python", "room": 3}} # a dictionary; each key has one value print(learner["batch"]["room"])

Example 2: A dict inside a dict

Read the outer key first, then the inner key.

batch = {"trainer": {"name": "Meera", "city": "Chennai"}} # a dictionary; each key has one value print(batch["trainer"]["city"])

Example 3: A list inside a dict

The list still uses a numeric index after you open the dictionary.

batch = {"skills": ["Python", "SQL"]} # a dictionary; each key has one value print(batch["skills"][0])

Example 4: Change a nested value

You can assign through both levels.

batch = {"trainer": {"name": "Meera"}} # a dictionary; each key has one value batch["trainer"]["name"] = "Arun" # change this one field print(batch)
If batch might be missing, read it with get and test the result before the second lookup.
Call Now 81900 98289