Python Dictionaries and Nested Dictionaries


What is a Dictionary in Python?

A dictionary in Python is an unordered, mutable, and indexed collection of key-value pairs. Each key must be unique, and values can be of any data type.



Dictionary Syntax

my_dict = {
    "name": "Alice",
    "age": 25,
    "profession": "Developer"
}


Example: Create and Print a Dictionary

person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print(person)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}


Access Dictionary Values

print(person["name"])        # John
print(person.get("age"))     # 30

The .get() method is safer—it returns None instead of an error if the key doesn't exist.



Add or Update Dictionary Items

person["email"] = "john@example.com"   # Add new
person["age"] = 31                     # Update


Remove Dictionary Items

person.pop("city")        # Removes key 'city'
del person["name"]        # Deletes key 'name'
person.clear()            # Empties the dictionary


Loop Through a Dictionary

for key in person:
    print(key, person[key])

# or use .items()
for key, value in person.items():
    print(key, value)


Useful Dictionary Methods

Method Description
.keys() Returns all keys
.values() Returns all values
.items() Returns key-value pairs as tuples
.get(key) Returns value of specified key
.update() Updates or adds key-value pairs
.pop(key) Removes specified key
.clear() Removes all items


Nested Dictionaries in Python

A nested dictionary is a dictionary inside another dictionary.

Example: Nested Dictionary

employees = {
    "emp1": {"name": "Alice", "age": 25},
    "emp2": {"name": "Bob", "age": 28},
    "emp3": {"name": "Charlie", "age": 30}
}

Accessing Nested Dictionary Values

print(employees["emp2"]["name"])  # Bob

Looping Through Nested Dictionary

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

Output:

Employee ID: emp1
  name: Alice
  age: 25
Employee ID: emp2
  name: Bob
  age: 28
Employee ID: emp3
  name: Charlie
  age: 30

Dictionary vs List vs Set vs Tuple

Feature Dictionary List Set Tuple
Syntax {"key": "value"} [1,2,3] {1,2,3} (1,2,3)
Ordered Yes (Python 3.7+) Yes No Yes
Mutable Yes Yes Yes No
Duplicate Values Yes Yes No Yes
Indexed By keys By position No By position