Python Dictionaries Explained

  • Admin
  • 1 min read

What is a Dictionary?

A dictionary stores data as key-value pairs, letting you look up a value instantly by its key instead of searching through a list by position.

student = { "name": "Meera", "age": 21, "courses": ["Math", "CS"] }

Accessing and Updating Values

print(student["name"]) # Meera student["age"] = 22 # update student["email"] = "m@x.com" # add new key

Avoiding KeyError with .get()

Accessing a missing key with [] raises an error. .get() returns None (or a default you choose) instead:

print(student.get("gpa")) # None print(student.get("gpa", "N/A")) # N/A

Looping Through a Dictionary

for key, value in student.items(): print(f"{key}: {value}")

Common Methods

  • .keys() — all keys
  • .values() — all values
  • .pop(key) — remove a key and return its value
  • key in dict — check existence
if "email" in student: print("We have an email on file")

Nested Dictionaries

Values can themselves be dictionaries or lists, which is how most real-world JSON-style data is modeled in Python.

users = { "u1": {"name": "Asha", "active": True}, "u2": {"name": "Rohan", "active": False} } print(users["u1"]["name"]) # Asha

Practice Exercise

Build a dictionary representing a product (name, price, in_stock), then write a loop that prints “In stock” or “Out of stock” based on the value.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated August 9, 2026.

Ask a question

Be specific about what you tried. Questions with a code sample and the exact error message are answered fastest.