Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
Python Beginner Free

Dictionaries

Lesson 5 of 14 · Collections 36%

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.

Choose an answer to continue.

Interview Questions

Hash tables map keys to storage locations via hash functions.

Up next

Conditionals

Lesson 6 of 14 · Control Flow