Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Python Dictionaries
Python Beginner FREE

Dictionaries

Lesson 2 of 14 Beginner Interactive

Dictionaries store key-value pairs with {}. Keys must be immutable and unique.

Access

dict[key] or dict.get(key, default)

Methods

  • keys(), values(), items()
  • update(), pop(), setdefault()

Syntax

PYTHON
person = {"name": "Alice", "age": 25}
print(person["name"])
print(person.get("phone", "N/A"))
person["email"] = "alice@mail.com"
for k, v in person.items():
    print(f"{k}: {v}")
Python Dictionaries
PYTHON
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

print("Name:", person["name"])
print("Get:", person.get("email", "not found"))

# Add / update
person["email"] = "alice@example.com"
print("Updated keys:", list(person.keys()))

# Iterate
for key, value in person.items():
    print(f"{key}: {value}")

# Nested
company = {
    "name": "SukhNexus",
    "employees": [
        {"name": "Bob", "role": "Developer"},
        {"name": "Eve", "role": "Designer"}
    ]
}
print("Role:", company["employees"][0]["role"])

Practice

1
Exercise

Count character frequencies in a string.

Answer
text = "hello"
for c in set(text):
    print(f"{c}: {text.count(c)}")

Quick Quiz

1

What does dict[key] do for missing keys?

Raises KeyError. Use .get() for safe access.

Interview Questions

Hash tables map keys to storage locations via hash functions.