Python

Python Dictionaries Explained

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.

Leave a Reply

Your email address will not be published. Required fields are marked *