Python Course
Dictionaries in Python
In this lesson, you will learn about Dictionaries — one of the most important and widely used data structures in Python. Dictionaries are used in almost every real-world Python program. By the end of this lesson, you will know how to create, read, update, and delete dictionary data with full confidence.
1. What is a Dictionary?
A dictionary stores data as key-value pairs. Instead of using a number (index) to find data like in a list, you use a meaningful key — like a word in a real dictionary that leads you to its meaning.
Think of it like a contact book on your phone. You search by a person's name (the key) and instantly get their phone number (the value). You do not need to scroll through every contact — you just look up the name directly.
Why does a dictionary exist? In real programs, data often has labels. A user has a name, an age, an email. A product has a title, a price, a category. Storing this kind of labelled data in a list is messy. A dictionary keeps it clean, readable, and fast to access.
Where are dictionaries used in real life?
- Storing user profile data (name, email, age)
- Representing a product in an online store
- Counting word frequency in a document
- Storing settings and configuration for an application
- Handling JSON data from web APIs (APIs send data as key-value pairs)
2. Creating a Dictionary
A dictionary is created using curly braces {}. Each item is a key-value pair written as key: value, and pairs are separated by commas. Keys are usually strings but can also be numbers or tuples. Values can be anything — strings, numbers, lists, even other dictionaries.
# A simple dictionary storing a student's details
# Left side of colon = key, Right side = value
student = {
"name" : "Riya",
"age" : 20,
"course": "Computer Science",
"grade" : "A"
}
# Print the whole dictionary
print(student)
What just happened?
- A dictionary called
studentwas created with 4 key-value pairs. - Keys are
"name","age","course", and"grade"— all strings. - Values are a mix of strings and a number. Dictionaries can hold any type of value.
- When printed, Python displays the dictionary with curly braces and colons exactly as you wrote it.
3. Accessing Values in a Dictionary
To get a value from a dictionary, you write the dictionary name followed by the key in square brackets — like student["name"]. You can also use the .get() method, which is safer because it does not crash your program if the key does not exist.
# Our student dictionary
student = {
"name" : "Riya",
"age" : 20,
"course": "Computer Science",
"grade" : "A"
}
# Method 1: Access using square brackets
print(student["name"]) # Gets the value for key "name"
print(student["age"]) # Gets the value for key "age"
# Method 2: Access using .get() — safer option
print(student.get("course")) # Returns the value
print(student.get("phone")) # Key doesn't exist → returns None
print(student.get("phone", "N/A")) # Key doesn't exist → returns "N/A" instead
20
Computer Science
None
N/A
What just happened?
student["name"]returns"Riya"— the value stored under the key"name".- If you use square brackets with a key that does not exist, Python raises a
KeyErrorand your program crashes. .get("phone")returnsNoneinstead of crashing — this is much safer in real programs..get("phone", "N/A")returns the default value"N/A"when the key is missing. This is the most professional way to access dictionary data.
4. Adding and Updating Dictionary Items
Dictionaries are mutable — you can change them after creation. To add a new key-value pair, simply assign a value to a new key. To update an existing key, assign a new value to it. Both use the same simple syntax.
# Starting with a basic product dictionary
product = {
"title": "Wireless Headphones",
"price": 2999
}
print("Before:", product)
# Adding a NEW key-value pair
product["brand"] = "SoundMax" # brand didn't exist — it gets added
product["in_stock"] = True # another new key added
# Updating an EXISTING key
product["price"] = 2499 # price already existed — it gets updated
print("After:", product)
After: {'title': 'Wireless Headphones', 'price': 2499, 'brand': 'SoundMax', 'in_stock': True}
What just happened?
- Assigning to a key that does not exist adds a brand new entry to the dictionary.
- Assigning to a key that already exists simply overwrites the old value — there is no separate "update" command needed.
- The price changed from
2999to2499, and two new keys were added — all in a natural, readable way.
5. Removing Items from a Dictionary
Python gives you several ways to remove items from a dictionary. Each method serves a slightly different purpose — use the one that fits your situation.
# A dictionary of app settings
settings = {
"theme" : "dark",
"language" : "English",
"font_size" : 14,
"auto_save" : True,
"debug_mode": False
}
# del — removes a specific key permanently
del settings["debug_mode"]
print("After del:", settings)
# pop() — removes a key AND returns its value (useful if you need the 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_removed = settings.popitem()
print("Last item removed:", last_removed)
print("After popitem:", settings)
# clear() — removes ALL items, leaves an empty dictionary
settings.clear()
print("After clear:", settings)
Removed value: 14
After pop: {'theme': 'dark', 'language': 'English', 'auto_save': True}
Last item removed: ('auto_save', True)
After popitem: {'theme': 'dark', 'language': 'English'}
After clear: {}
What just happened?
del settings["debug_mode"]— permanently removes the key. There is no return value. Use this when you just want the key gone.settings.pop("font_size")— removes the key AND gives you back its value (14). Use this when you need to use the value after removing it.settings.popitem()— removes and returns the last inserted item as a tuple. Useful when processing a dictionary like a stack.settings.clear()— wipes the entire dictionary clean. The variable still exists, it just becomes empty{}.
6. Essential Dictionary Methods
Python dictionaries come with several built-in methods that make working with them very easy. The three most important are .keys(), .values(), and .items(). You will use these constantly in real programs.
# A dictionary of country capitals
capitals = {
"India" : "New Delhi",
"Japan" : "Tokyo",
"France" : "Paris",
"Brazil" : "Brasília"
}
# .keys() — gives all the keys
print("Keys:", capitals.keys())
# .values() — gives all the values
print("Values:", capitals.values())
# .items() — gives all key-value pairs as tuples
print("Items:", capitals.items())
# Practical use: convert keys to a regular list
key_list = list(capitals.keys())
print("Keys as list:", key_list)
Values: dict_values(['New Delhi', 'Tokyo', 'Paris', 'Brasília'])
Items: dict_items([('India', 'New Delhi'), ('Japan', 'Tokyo'), ('France', 'Paris'), ('Brazil', 'Brasília')])
Keys as list: ['India', 'Japan', 'France', 'Brazil']
What just happened?
.keys()returns a specialdict_keysview of all keys. You can wrap it inlist()to get a plain list..values()returns all the values. This is useful when you want to process or search through values alone..items()returns each key-value pair as a tuple — this is what you use when looping through a dictionary to get both key and value at the same time.
7. Looping Through a Dictionary
You will often need to go through every item in a dictionary — for example, to display all user data, process all settings, or search for a specific value. Python makes this very clean using a for loop with .items().
# A dictionary of an employee's details
employee = {
"name" : "Arjun",
"department": "Engineering",
"salary" : 95000,
"remote" : True
}
# Loop 1: Loop through keys only
print("--- Keys ---")
for key in employee:
print(key)
# Loop 2: Loop through values only
print("\n--- Values ---")
for value in employee.values():
print(value)
# Loop 3: Loop through both key and value together (most useful)
print("\n--- Key : Value ---")
for key, value in employee.items():
print(f" {key} : {value}")
name
department
salary
remote
--- Values ---
Arjun
Engineering
95000
True
--- Key : Value ---
name : Arjun
department : Engineering
salary : 95000
remote : True
What just happened?
- Looping with
for key in employeeautomatically goes through the keys one by one. - Looping with
.values()gives only the values — useful when keys are not needed. - The
for key, value in employee.items()pattern is the most common and powerful — it unpacks each pair into two variables simultaneously. You will use this in almost every real program involving dictionaries.
8. Checking if a Key Exists
Before accessing a key, it is good practice to check whether it actually exists in the dictionary. This prevents your program from crashing with a KeyError. You use the in and not in keywords for this — exactly like with lists and tuples.
# A user profile dictionary
user = {
"username": "dev_learner",
"email" : "learner@example.com",
"age" : 24
}
# Check if a key exists before using it
if "email" in user:
print("Email found:", user["email"])
if "phone" not in user:
print("Phone number is not stored in this profile.")
# A practical example: only update if key is missing
if "country" not in user:
user["country"] = "India" # Add a default value
print("Country set to default:", user["country"])
Phone number is not stored in this profile.
Country set to default: India
What just happened?
"email" in userreturnsTruebecause the key exists — so theifblock runs safely."phone" not in userreturnsTruebecause there is no phone key — so we print a message instead of crashing.- The third block shows a real-world pattern: check first, then set a default. This is used constantly when handling user data or API responses where some fields might be missing.
9. Nested Dictionaries
A nested dictionary is a dictionary that contains other dictionaries as values. This lets you represent complex, structured data — like multiple user records, product catalogues, or configuration files — in a single clean structure.
# A dictionary containing details for two students
# Each student's data is itself a dictionary (nested)
students = {
"S001": {
"name" : "Priya",
"marks" : 88,
"grade" : "B+"
},
"S002": {
"name" : "Kiran",
"marks" : 95,
"grade" : "A"
}
}
# Access the full record of student S001
print("S001 record:", students["S001"])
# Access a specific field — first key (student ID), then inner key (field name)
print("S002 Name:", students["S002"]["name"])
print("S002 Marks:", students["S002"]["marks"])
# Loop through all students and display their info neatly
print("\nAll Students:")
for student_id, details in students.items():
print(f" ID: {student_id} | Name: {details['name']} | Grade: {details['grade']}")
S002 Name: Kiran
S002 Marks: 95
All Students:
ID: S001 | Name: Priya | Grade: B+
ID: S002 | Name: Kiran | Grade: A
What just happened?
students["S001"]returns the entire inner dictionary for that student.students["S002"]["name"]uses double key access — first get the student record, then get the name field within it.- The loop unpacks each entry into
student_idanddetails. Sincedetailsis itself a dictionary, you access its fields withdetails['name']etc. - This pattern is almost identical to how real JSON data from web APIs is structured and processed.
10. Dictionary Comprehension
Dictionary comprehension is a short, clean way to create a dictionary in a single line using a loop. Instead of writing multiple lines of code to build a dictionary, you write one compact expression. It is the same idea as list comprehension — but produces a dictionary instead.
# Regular way — creating a dictionary with a for loop (longer)
squares_normal = {}
for n in range(1, 6):
squares_normal[n] = n * n
print("Normal way:", squares_normal)
# Comprehension way — exact same result in ONE line
# Format: {key: value for item in collection}
squares_comp = {n: n * n for n in range(1, 6)}
print("Comprehension:", squares_comp)
# Practical example: make all keys uppercase from a list of words
words = ["python", "data", "science", "loop"]
upper_dict = {word: word.upper() for word in words}
print("Uppercase dict:", upper_dict)
# With a condition: only include even numbers
even_squares = {n: n * n for n in range(1, 11) if n % 2 == 0}
print("Even squares:", even_squares)
Comprehension: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Uppercase dict: {'python': 'PYTHON', 'data': 'DATA', 'science': 'SCIENCE', 'loop': 'LOOP'}
Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
What just happened?
- Both the normal loop and the comprehension produce the exact same dictionary — the comprehension is just shorter and more Pythonic.
{word: word.upper() for word in words}— for each word, the key is the lowercase word and the value is its uppercase version.- Adding
if n % 2 == 0at the end filters the loop — only even numbers are included in the resulting dictionary. - You will see dictionary comprehensions everywhere in professional Python code — in data processing, web development, and data science.
11. Merging Dictionaries with update()
The .update() method lets you merge one dictionary into another. It adds all key-value pairs from the second dictionary into the first. If a key already exists, the value gets overwritten. This is very useful when combining settings, updating user profiles, or merging API response data.
# Base profile — the original data we have
base_profile = {
"username": "coder_99",
"email" : "coder@example.com",
"plan" : "free"
}
# New data coming in — maybe from a form submission or upgrade action
updates = {
"plan" : "premium", # This key exists — will be overwritten
"country" : "India", # This key is new — will be added
"verified": True # This key is new — will be added
}
# Merge updates into base_profile
base_profile.update(updates)
print("Updated profile:")
for key, value in base_profile.items():
print(f" {key}: {value}")
username: coder_99
email: coder@example.com
plan: premium
country: India
verified: True
What just happened?
planwas"free"in the original — afterupdate(), it became"premium"because the key existed and was overwritten.countryandverifieddid not exist before — they were both added as new entries.usernameandemailwere not in the updates dictionary, so they stayed unchanged.- This is the standard pattern for updating user records in web applications, databases, and configuration systems.
12. Copying a Dictionary
In Python, if you assign a dictionary to a new variable using =, both variables point to the exact same dictionary in memory. Changing one will change the other. To get an independent copy, you must use the .copy() method.
# Original dictionary
original = {"item": "Laptop", "price": 80000}
# WRONG way — both variables point to the same dictionary
wrong_copy = original
wrong_copy["price"] = 999 # This also changes 'original'!
print("Original after wrong copy change:", original)
# -----------------------------------------------
# Reset original
original = {"item": "Laptop", "price": 80000}
# CORRECT way — use .copy() to get an independent copy
correct_copy = original.copy()
correct_copy["price"] = 999 # Only changes correct_copy
print("Original stays safe:", original)
print("The copy was changed:", correct_copy)
Original stays safe: {'item': 'Laptop', 'price': 80000}
The copy was changed: {'item': 'Laptop', 'price': 999}
What just happened?
- Using
wrong_copy = originaldoes NOT create a new dictionary — it just creates a second name that points to the same dictionary. Changing one changes both. original.copy()creates a brand new, independent dictionary. Changingcorrect_copyhas zero effect onoriginal.- This is one of the most common beginner bugs in Python. Always use
.copy()when you want an independent duplicate.
13. Real-World Example — Word Frequency Counter
One of the most classic and practical uses of a dictionary is counting how many times each word appears in a piece of text. This is used in search engines, spam filters, text analysis tools, and language processing applications.
# A sample sentence
sentence = "python is great python is easy python is fun to learn"
# Split the sentence into individual words
words = sentence.split() # Creates a list of words
# Count each word using a dictionary
word_count = {} # Start with an empty dictionary
for word in words:
if word in word_count:
word_count[word] += 1 # Word seen before — increase count by 1
else:
word_count[word] = 1 # Word seen first time — set count to 1
# Display the results
print("Word Frequency:")
for word, count in word_count.items():
print(f" '{word}' → {count} time(s)")
'python' → 3 time(s)
'is' → 3 time(s)
'great' → 1 time(s)
'easy' → 1 time(s)
'fun' → 1 time(s)
'to' → 1 time(s)
'learn' → 1 time(s)
What just happened?
sentence.split()breaks the string into a list of individual words separated by spaces.- For each word, the code checks if it is already a key in
word_count. If yes — increase the count. If no — add it with a count of1. - After the loop, the dictionary holds every unique word as a key and its total count as the value.
- This exact logic is used in real applications like email spam detection, SEO keyword analysis, and natural language processing.
14. Lesson Summary
Here is a complete reference of everything covered in this lesson. Keep this as a quick-access cheat sheet while building programs.
| Concept | Syntax / Example | What It Does |
|---|---|---|
| Create dictionary | d = {"key": "value"} | Stores key-value pairs in curly braces |
| Access with key | d["key"] | Returns value; crashes if key missing |
| Safe access | d.get("key", default) | Returns default if key is missing |
| Add / Update | d["key"] = value | Adds if new; overwrites if exists |
| Delete key | del d["key"] | Removes key permanently |
| Remove & get value | d.pop("key") | Removes key and returns its value |
| Remove last item | d.popitem() | Removes & returns last inserted pair |
| Clear all | d.clear() | Empties the dictionary |
| Get all keys | d.keys() | Returns a view of all keys |
| Get all values | d.values() | Returns a view of all values |
| Get all pairs | d.items() | Returns key-value pairs as tuples |
| Check key exists | "key" in d | Returns True or False |
| Merge dictionaries | d1.update(d2) | Adds d2 into d1; overwrites matching keys |
| Copy dictionary | d2 = d1.copy() | Creates an independent copy |
| Nested dictionary | d["key"]["inner_key"] | Dictionary inside a dictionary |
| Comprehension | {k: v for k, v in ...} | Build a dictionary in one line |
🧪 Practice Questions
Type your answers below. These are based only on what you learned in this lesson.
1. A dictionary stores data as __________ pairs.
2. Which method safely accesses a dictionary value and returns a default if the key is missing?
3. Which method removes a key from a dictionary AND returns its value?
4. Which method returns all key-value pairs of a dictionary as tuples?
5. To create an independent duplicate of a dictionary without affecting the original, use the __________ method.
🎯 Quiz — Test Your Understanding
Q1. What error does Python raise when you access a dictionary key using square brackets and the key does not exist?
Q2. What does a dictionary look like after calling .clear() on it?
Q3. You have d = {"name": "Alex", "age": 25}. What does "age" in d return?
Q4. Which method merges all key-value pairs from one dictionary into another?
Q5. How many key-value pairs does this dictionary have? d = {"a": 1, "b": 2, "c": 3}