
Python Course
Dictionaries in Python
A dictionary stores data as key-value pairs. Instead of using a number to find an item like in a list, you use a meaningful label — the key — to retrieve its value instantly. Think of it like a contact book: you search by a person's name (the key) and get their phone number (the value).
Dictionaries are used in almost every real Python program — storing user profiles, representing products, handling JSON from APIs, counting word frequency, and managing application settings. Mastering dictionaries is one of the most valuable skills in Python.
Creating a Dictionary
Dictionaries are created using curly braces {}. Each item is written as key: value and pairs are separated by commas. Keys are usually strings, but values can be anything.
student = {
"name" : "Riya",
"age" : 20,
"course": "Computer Science",
"grade" : "A"
}
print(student)
- Curly braces
{}define a dictionary. - Each entry has a key (left of the colon) and a value (right of the colon).
- Values can be any type — strings, numbers, booleans, lists, even other dictionaries.
Accessing Values
To get a value, write the dictionary name followed by the key in square brackets. For safer access, use the .get() method — it returns a default instead of crashing if the key does not exist.
student = {"name": "Riya", "age": 20, "course": "Computer Science"}
# Square bracket access — crashes if key missing
print(student["name"])
print(student["age"])
# .get() — safe access with optional default
print(student.get("course")) # Returns the value
print(student.get("phone")) # Key missing → returns None
print(student.get("phone", "N/A")) # Key missing → returns "N/A"
- Square brackets raise a
KeyErrorif the key does not exist. Use them when you are certain the key is there. .get(key, default)is the professional choice — no crashes, clean fallback values.
Adding and Updating Items
Dictionaries are mutable. Assigning a value to a new key adds it. Assigning to an existing key overwrites the old value. Both use the same syntax.
product = {"title": "Wireless Headphones", "price": 2999}
print("Before:", product)
# Adding new keys
product["brand"] = "SoundMax"
product["in_stock"] = True
# Updating an existing key
product["price"] = 2499
print("After:", product)
Removing Items
Python provides several ways to remove items — each suited to a slightly different situation.
settings = {"theme": "dark", "language": "English", "font_size": 14, "auto_save": True, "debug_mode": False}
# del — removes a key permanently, no return value
del settings["debug_mode"]
print("After del:", settings)
# pop() — removes a key and returns its value
removed_font = settings.pop("font_size")
print("Removed value:", removed_font)
print("After pop:", settings)
# popitem() — removes the last inserted key-value pair
last = settings.popitem()
print("Last item removed:", last)
# clear() — removes everything, leaves an empty dict
settings.clear()
print("After clear:", settings)
- Use
delwhen you just want the key gone. - Use
pop()when you need the value after removing it. popitem()removes the last inserted pair as a tuple.clear()empties the dictionary — the variable still exists, it just becomes{}.
Essential Dictionary Methods
The three most important methods are .keys(), .values(), and .items(). You will use these constantly in real programs.
capitals = {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris", "Brazil": "Brasília"}
print("Keys :", capitals.keys())
print("Values:", capitals.values())
print("Items :", capitals.items())
# Convert to a plain list
key_list = list(capitals.keys())
print("Keys as list:", key_list)
Looping Through a Dictionary
Use a for loop to go through every item. The .items() pattern is the most useful — it gives you both the key and value at the same time.
employee = {"name": "Arjun", "department": "Engineering", "salary": 95000, "remote": True}
# Keys only
for key in employee:
print(key)
# Values only
for value in employee.values():
print(value)
# Key and value together (most common)
for key, value in employee.items():
print(f" {key}: {value}")
Checking if a Key Exists
Use in and not in to check whether a key exists before accessing it. This prevents KeyError crashes.
user = {"username": "dev_learner", "email": "learner@example.com", "age": 24}
if "email" in user:
print("Email found:", user["email"])
if "phone" not in user:
print("Phone not stored in this profile.")
# Set a default if key is missing
if "country" not in user:
user["country"] = "India"
print("Country set to default:", user["country"])
Nested Dictionaries
A dictionary can contain other dictionaries as values. This is how real JSON data from APIs is structured — and how you store multiple related records in one clean structure.
students = {
"S001": {"name": "Priya", "marks": 88, "grade": "B+"},
"S002": {"name": "Kiran", "marks": 95, "grade": "A"}
}
# Access an entire inner record
print("S001 record:", students["S001"])
# Access a specific field — outer key then inner key
print("S002 Name :", students["S002"]["name"])
print("S002 Marks:", students["S002"]["marks"])
# Loop through all students
for student_id, details in students.items():
print(f" {student_id} | {details['name']} | {details['grade']}")
Dictionary Comprehension
Dictionary comprehension builds a dictionary in a single line using a loop — the same idea as list comprehension but produces a dictionary instead.
# Regular way (longer)
squares_normal = {}
for n in range(1, 6):
squares_normal[n] = n * n
print("Normal:", squares_normal)
# Comprehension way — same result in one line
squares_comp = {n: n * n for n in range(1, 6)}
print("Comprehension:", squares_comp)
# With a condition — only even numbers
even_squares = {n: n * n for n in range(1, 11) if n % 2 == 0}
print("Even squares:", even_squares)
Merging Dictionaries with update()
The .update() method merges one dictionary into another. Existing keys are overwritten; new keys are added.
base_profile = {"username": "coder_99", "email": "coder@example.com", "plan": "free"}
updates = {"plan": "premium", "country": "India", "verified": True}
base_profile.update(updates)
for key, value in base_profile.items():
print(f" {key}: {value}")
Copying a Dictionary
Using = does NOT create a separate copy — both variables point to the same dictionary. Use .copy() for an independent duplicate.
original = {"item": "Laptop", "price": 80000}
# Wrong — both point to the same dictionary
wrong_copy = original
wrong_copy["price"] = 999
print("Original after wrong copy change:", original)
# Reset
original = {"item": "Laptop", "price": 80000}
# Correct — independent copy
correct_copy = original.copy()
correct_copy["price"] = 999
print("Original stays safe:", original)
print("Copy changed:", correct_copy)
Real World Example — Word Frequency Counter
One of the most classic uses of a dictionary — counting how many times each word appears in a piece of text. This logic is used in search engines, spam filters, and text analysis tools.
sentence = "python is great python is easy python is fun to learn"
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(f" '{word}' → {count} time(s)")
Quick Reference Table
| Concept | Syntax | What It Does |
|---|---|---|
| Create | d = {"key": "value"} | Stores key-value pairs |
| Access | d["key"] | Returns value; KeyError if missing |
| Safe access | d.get("key", default) | Returns default if key missing |
| Add / Update | d["key"] = value | Adds if new; overwrites if exists |
| Delete | del d["key"] | Removes key permanently |
| Remove + get value | d.pop("key") | Removes and returns value |
| All keys | d.keys() | View of all keys |
| All values | d.values() | View of all values |
| All pairs | d.items() | Key-value pairs as tuples |
| Key exists | "key" in d | Returns True or False |
| Merge | d1.update(d2) | Adds d2 into d1 |
| Copy | d2 = d1.copy() | Independent duplicate |
| Nested access | d["key"]["inner"] | Dictionary inside a dictionary |
Practice
A dictionary stores data as __________ pairs.
Which method safely accesses a dictionary value and returns a default if the key is missing?
Which method removes a key from a dictionary AND returns its value?
Which method returns all key-value pairs as tuples?
To create an independent duplicate of a dictionary, use the __________ method.
Quick Quiz
What error is raised when you access a missing key using square brackets?
What does a dictionary look like after calling .clear()?
Given d = {"name": "Alex", "age": 25}, what does "age" in d return?
Which method merges all key-value pairs from one dictionary into another?
How many key-value pairs does d = {"a": 1, "b": 2, "c": 3} have?