Placement Prep

Python Nested Dictionaries with Example Programs

Create, access, modify, and iterate Python nested dictionaries with worked code examples. Covers .get() safety and patterns from placement coding rounds.

By FACE Prep Team 5 min read
python nested-dictionaries placement-prep data-structures coding-examples python-dict

A nested dictionary in Python stores dictionaries as values inside another dictionary, giving you a clean structure for hierarchical records like employee tables, product catalogs, or parsed API responses.

What Is a Nested Dictionary in Python

The Python mapping-types documentation defines a dict as a mapping from hashable keys to arbitrary objects. When those objects are themselves dicts, you get a nested structure: one dictionary living inside another.

The minimal form looks like this:

nested_dict = {
    'dict1': {'key1': 'value1', 'key2': 'value2'},
    'dict2': {'key3': 'value3', 'key4': 'value4'}
}

The outer dictionary has two keys, 'dict1' and 'dict2'. Each value is a second-level dictionary with its own key-value pairs.

A closer-to-real-life form uses integer IDs as outer keys:

employees = {
    101: {"name": "Ravi",  "job": "Software Developer", "city": "Bangalore"},
    102: {"name": "Meena", "job": "Data Analyst",        "city": "Chennai"}
}

Employee ID is the outer key; the record fields sit in the inner dict. This is the format that placement coding rounds on TCS NQT, Infosys InfyTQ, and AMCAT-based tests use for employee-record and inventory problems. If loops and conditionals feel shaky, revisit Python basic programs before continuing; nested dicts require confident use of both.

Creating Nested Dictionaries

Two approaches: write everything at once with literal syntax, or build the inner dicts one field at a time.

Literal syntax

All inner dicts written directly inside the outer dict:

products = {
    'P001': {'name': 'Laptop',   'price': 55000, 'stock': 12},
    'P002': {'name': 'Mouse',    'price': 750,   'stock': 80},
    'P003': {'name': 'Keyboard', 'price': 1200,  'stock': 45}
}
print(products)

This is the fastest to write in a timed test. Know the structure in advance, write it all at once.

Step-by-step assignment

Useful when you’re reading data row by row from a loop:

employees = {}
employees[101] = {}
employees[101]['name'] = 'Ravi'
employees[101]['job']  = 'Software Developer'
employees[101]['city'] = 'Bangalore'

# Or add a complete record in one assignment:
employees[102] = {'name': 'Meena', 'job': 'Data Analyst', 'city': 'Chennai'}

Both produce identical structures. In placement questions that say “read N employee records and store them,” the step-by-step loop method is what you implement. In questions that give you the data upfront, the literal form is quicker.

Reading, Modifying, and Safe Access

Reading a value by chaining keys

The first key selects the inner dict; the second key selects the field within it:

print(employees[101]['name'])   # Ravi
print(employees[102]['city'])   # Chennai

You can chain as many levels deep as your structure requires. For a three-level dict data = {'org': {'dept': {'team': 'backend'}}}, you would write data['org']['dept']['team'].

Safe access with .get()

Direct indexing raises KeyError if the key does not exist. When input data is incomplete, use .get() with a fallback:

result = employees.get(105, {}).get('job', 'Not found')
print(result)   # Not found

The Python data structures tutorial covers .get(), .setdefault(), and .update() in full. These three methods appear regularly in placement problems involving dicts. The pattern outer.get(key, {}).get(inner_key, default) is worth memorising.

Modifying an existing value

Direct assignment overwrites only the specified field:

employees[101]['city'] = 'Hyderabad'
print(employees[101]['city'])   # Hyderabad

No other field in employees[101] is touched.

Adding a new field to an inner dict

Assign to a key that does not exist yet, and Python creates it:

employees[101]['dept'] = 'Backend'
print(employees[101])
# {'name': 'Ravi', 'job': 'Software Developer', 'city': 'Hyderabad', 'dept': 'Backend'}

Merging records with .update()

.update() merges one dict into another. At the inner-dict level, it adds or overwrites fields without affecting keys you did not mention:

employees[102].update({'city': 'Pune', 'dept': 'Analytics'})
print(employees[102])
# {'name': 'Meena', 'job': 'Data Analyst', 'city': 'Pune', 'dept': 'Analytics'}

Deleting Entries

Delete one field from an inner dict

del employees[101]['dept']
print(employees[101])
# {'name': 'Ravi', 'job': 'Software Developer', 'city': 'Hyderabad'}

Delete an entire inner dict

del employees[102]
print(employees)
# {101: {'name': 'Ravi', 'job': 'Software Developer', 'city': 'Hyderabad'}}

Safe deletion with .pop()

del raises KeyError if the key is absent. Use .pop(key, None) when the key might not exist:

removed = employees.pop(103, None)
print(removed)   # None — no error raised

.pop() also returns the removed value, which makes it useful when you need to extract a record and delete it in one step.

Iterating Over Nested Dictionaries

The standard traversal pattern uses two .items() loops, one for the outer dict and one for each inner dict:

for emp_id, details in employees.items():
    print(f"Employee ID: {emp_id}")
    for field, value in details.items():
        print(f"  {field}: {value}")

For employees[101], this prints:

  • Employee ID: 101
  • name: Ravi
  • job: Software Developer
  • city: Hyderabad

Placement questions frequently ask you to “print all employee details” or “find the employee whose salary is highest.” Both use this loop structure as the starting point.

To search for a specific record instead of printing all:

target_city = 'Hyderabad'
for emp_id, details in employees.items():
    if details.get('city') == target_city:
        print(f"Employee {emp_id} is in {target_city}")

This replaces the inner loop with a condition check. The .get() on the inner dict prevents a crash if 'city' is missing from any record.

Practical Examples for Placement Coding Rounds

Example 1: Find the student with the highest CGPA

students = {
    'S001': {'name': 'Arun',  'cgpa': 8.4},
    'S002': {'name': 'Divya', 'cgpa': 9.1},
    'S003': {'name': 'Kabir', 'cgpa': 7.8}
}

top_id = max(students, key=lambda sid: students[sid]['cgpa'])
print(students[top_id]['name'], students[top_id]['cgpa'])
# Divya 9.1

max() with a key function avoids a manual loop. The lambda reaches into the inner dict to compare CGPA values across all records.

Example 2: Group and count records by a field

city_count = {}
for details in employees.values():
    city = details.get('city', 'Unknown')
    city_count[city] = city_count.get(city, 0) + 1

print(city_count)
# {'Hyderabad': 1}

This builds a flat summary dict from a nested source dict. The .get(city, 0) + 1 pattern avoids a KeyError on the first occurrence of each city. Placement rounds that involve aggregation tasks use this loop structure.

Example 3: Convert to JSON for API work

import json

data = {
    101: {"name": "Ravi",  "job": "Software Developer"},
    102: {"name": "Meena", "job": "Data Analyst"}
}

print(json.dumps(data, indent=2))

json.dumps() converts the nested dict to a formatted JSON string. The reverse, json.loads(), parses a JSON string back into a Python nested dict. Any JSON API response you receive is structurally identical to what you built in this guide.

A calculator program in Python uses a flat dict for operator dispatch; nested dicts are the next layer once each entry needs multiple attributes rather than a single value.

The connection to API work is direct: json.loads() returns exactly the nested-dict structure practiced in the examples above. TinkerLLM puts that to work on day one: its first build project parses a live API response, and the details.get('field', default) pattern from Example 2 is the mechanism you reach for.

Primary sources

Frequently asked questions

What is the difference between a dict and a nested dict in Python?

A standard dict maps keys to values such as strings or numbers. A nested dict maps keys to other dicts, letting you attach multiple attributes to each top-level key — for example, an employee ID mapped to a record with name, job, and city fields.

How do I access a value in a nested dictionary without a KeyError?

Use chained .get() calls: employees.get(101, {}).get('name', 'Unknown'). If key 101 is absent, .get(101, {}) returns an empty dict, and the second .get() returns 'Unknown' instead of raising an error.

Can nested dictionaries have more than two levels?

Yes. Python allows arbitrary nesting depth. A three-level example: data = {'org': {'dept': {'team': 'backend'}}}. Access the innermost value with data['org']['dept']['team'].

How do I iterate over all entries in a nested dictionary?

Use a nested loop: for key, inner_dict in outer.items() handles the top level, then for field, val in inner_dict.items() walks each attribute. This is the standard traversal pattern in placement questions.

How do I convert a nested dictionary to JSON in Python?

Import json and call json.dumps(nested_dict, indent=2). Python dicts and JSON objects share the same key-value structure, so the conversion is direct with no data loss for string, number, list, and boolean values.

When should I use a nested dict rather than a list of dicts?

Use a nested dict when you need direct key-based lookup (employees[101] is O(1)). Use a list of dicts when order matters or when you need to iterate all records in sequence without looking them up by a specific key.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF