Learn Python Dictionaries: Complete Guide with Examples

Python Dictionaries Explained

πŸ“˜ Python Dictionaries
Complete Guide

Keys · Values · Methods · Nested · Looping · Real-Life Project

Section 01
What is a Dictionary in Python?

A dictionary in Python is a collection that stores data as key-value pairs. Each item has a unique key used to access its value — just like a real dictionary where each word (key) has a meaning (value). Dictionaries are written using curly braces { } with a colon : separating keys and values.

πŸ’» Example:
Python
student = {

    "name"  : "Ali",

    "age"   : 18,

    "grade" : "A"

}

print(student)
πŸ‘† Output:
{'name': 'Ali', 'age': 18, 'grade': 'A'}
Stores data as key: value pairs
Keys must be unique and immutable
Values can be any data type
Ordered (Python 3.7+) and mutable
Section 02
Characteristics of Dictionary
FeatureDescription
key-value pairsEach item has a key and a value
Unique keysNo two items can have the same key
MutableCan add, change, remove items
OrderedItems keep insertion order (Python 3.7+)
Keys immutableKeys must be str, int, or tuple
Values any typeValues can be any data type
No indexAccess via key, not position number
πŸ’‘ Dictionary keys are like labels — you use the label to find the value. It is much more readable than using index numbers.
Section 03
Creating a Dictionary (Different Ways)
πŸ’» Different ways to create:
Python
# Method 1 — curly braces

d1 = {"name": "Ali", "age": 18}

# Method 2 — dict() constructor

d2 = dict(name="Sara", age=20)

# Method 3 — empty dictionary

d3 = {}

# Method 4 — from keys list

keys = ["a", "b", "c"]

d4   = dict.fromkeys(keys, 0)

print(d1)   # {'name': 'Ali', 'age': 18}

print(d2)   # {'name': 'Sara', 'age': 20}

print(d4)   # {'a': 0, 'b': 0, 'c': 0}
Section 04
Accessing Values (get(), keys, brackets)

You can access values using the key inside square brackets dict["key"], or using the get() method. The difference is important — if the key doesn't exist, dict["key"] raises a KeyError, but dict.get("key") returns None safely.

πŸ’» Example:
Python
student = {"name": "Ali", "age": 18}

# Method 1 — square brackets

print(student["name"])        # Ali

# Method 2 — get() (safe)

print(student.get("age"))     # 18

print(student.get("grade"))   # None

# Default value with get()

print(student.get("grade", "N/A")) # N/A
πŸ’‘ Always use get() when the key might not exist. It prevents crashes and is safer than dict["key"].
Section 05
Adding New Items to a Dictionary

Adding a new item to a dictionary is done by assigning a value to a new key. If the key already exists, the value is updated. If it doesn't exist, a new key-value pair is added. You can also use the update() method to add multiple items at once.

πŸ’» Example:
Python
student = {"name": "Ali", "age": 18}

# Add one item

student["grade"] = "A"

# Add multiple using update()

student.update({"city": "Karachi", "score": 95})

print(student)
πŸ‘† Output:
{'name': 'Ali', 'age': 18, 'grade': 'A', 'city': 'Karachi', 'score': 95}
Section 06
Updating Existing Values

Updating a value in a dictionary is done by accessing the key and assigning a new value. The update() method can also update existing keys. If the key exists, the value is overwritten. If it doesn't exist, a new item is created.

πŸ’» Example:
Python
student = {"name": "Ali", "age": 18, "grade": "B"}

# Update single value

student["grade"] = "A"

student["age"]   = 19

# Update using update()

student.update({"grade": "A+", "age": 20})

print(student)
πŸ‘† Output:
{'name': 'Ali', 'age': 20, 'grade': 'A+'}
Section 07
Removing Items (pop, popitem, del, clear)

Python provides four ways to remove items from a dictionary — pop() removes by key and returns the value, popitem() removes the last inserted item, del deletes by key or the whole dictionary, and clear() removes all items at once.

Python
d = {"name": "Ali", "age": 18, "city": "Karachi"}

# pop() — remove by key

d.pop("age")

print(d)    # {'name': 'Ali', 'city': 'Karachi'}

# popitem() — remove last item

d.popitem()

print(d)    # {'name': 'Ali'}

# del — delete by key

del d["name"]

print(d)    # {}

# clear() — empty the dictionary

d.clear()

print(d)    # {}
⚠️ pop() raises KeyError if the key doesn't exist. Use pop("key", None) to avoid the error.
Section 08
Looping Through a Dictionary

You can loop through a dictionary to access keys, values, or both. Use for key in dict to loop through keys, dict.values() for values, and dict.items() to get both keys and values at the same time.

Python
student = {"name": "Ali", "age": 18, "grade": "A"}

# Loop through keys

for key in student:

    print(key)

# Loop through values

for val in student.values():

    print(val)

# Loop through both (key + value)

for k, v in student.items():

    print(k, ":", v)
πŸ‘† items() Output:
name : Ali
age : 18
grade : A
Section 09
Dictionary Methods (keys, values, items, update)
MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns all key-value pairs
get(key)Returns value safely
update()Adds or updates multiple items
pop(key)Removes item by key
popitem()Removes last item
clear()Removes all items
copy()Makes a copy of dict
fromkeys()Creates dict from keys list
setdefault()Returns value or sets default
πŸ’» Example:
Python
d = {"a": 1, "b": 2, "c": 3}

print(d.keys())     # dict_keys(['a','b','c'])

print(d.values())   # dict_values([1, 2, 3])

print(d.items())    # dict_items([('a',1)...])
Section 10
Nested Dictionaries

A nested dictionary is a dictionary that contains another dictionary as its value. This is useful for representing complex, structured data like a database of students, a school roster, or product catalogs. You access values using chained keys.

πŸ’» Example:
Python
school = {

    "student1": {"name": "Ali",  "age": 18},

    "student2": {"name": "Sara", "age": 17},

    "student3": {"name": "John", "age": 19}

}

print(school["student1"]["name"])  # Ali

print(school["student2"]["age"])   # 17

# Loop through nested

for sid, info in school.items():

    print(sid, ":", info["name"])
Section 11
Dictionary inside List & List inside Dictionary
▶ List of Dictionaries:
Python
students = [

    {"name": "Ali",  "grade": "A"},

    {"name": "Sara", "grade": "B"},

    {"name": "John", "grade": "A+"}

]

for s in students:

    print(s["name"], "-", s["grade"])
πŸ‘† Output:
Ali - A
Sara - B
John - A+
▶ Dictionary with List values:
Python
marks = {

    "Ali":  [85, 90, 78],

    "Sara": [92, 88, 95]

}

print(sum(marks["Ali"]))    # 253

print(max(marks["Sara"]))  # 95
Section 12
Copying a Dictionary (copy vs =)

Using d2 = d1 does NOT create a real copy — both variables point to the same dictionary. Changes in one affect the other. Always use copy() or dict() to make an independent copy.

Python
d1 = {"name": "Ali", "age": 18}

# ❌ Wrong — reference copy

d2 = d1

d2["age"] = 99

print(d1)   # {'name':'Ali', 'age':99} ← changed!

# ✅ Correct — true copy

d3 = d1.copy()

d3["age"] = 20

print(d1)   # unchanged
⚠️ Always use .copy() to make independent copies of dictionaries.
Section 13
Dictionary Length (len)

The len() function returns the number of key-value pairs in a dictionary. You can also use it to check if a dictionary is empty before performing operations on it.

πŸ’» Example:
Python
student = {"name": "Ali", "age": 18, "grade": "A"}

print(len(student))    # 3

# Check if empty

if len(student) == 0:

    print("Dictionary is empty")

else:

    print("Has", len(student), "items")
πŸ‘† Output:
3
Has 3 items
Section 14
Checking Key Existence (in keyword)

Use the in keyword to check if a key exists in a dictionary before accessing or removing it. This prevents KeyError exceptions. You can also use not in to check if a key does NOT exist.

πŸ’» Example:
Python
student = {"name": "Ali", "age": 18}

# Check if key exists

print("name"  in student)      # True

print("grade" in student)     # False

print("grade" not in student) # True

# Safe access pattern

if "name" in student:

    print(student["name"])        # Ali
πŸ’‘ Note: in checks keys only, not values. To check values, use: value in dict.values()
Section 15
Real-Life Project Example (Student Database)

Here is a complete real-life mini project — a Student Database system built using dictionaries. It stores student records, allows searching by ID, adding new students, and displaying the full database.

πŸ’» Student Database:
Python
database = {

    "S001": {"name": "Ali",  "age": 18, "grade": "A"},

    "S002": {"name": "Sara", "age": 17, "grade": "B"},

    "S003": {"name": "John", "age": 19, "grade": "A+"}

}

# Search student by ID

sid = "S002"

if sid in database:

    info = database[sid]

    print(f"Name : {info['name']}")

    print(f"Age  : {info['age']}")

    print(f"Grade: {info['grade']}")

# Add new student

database["S004"] = {"name": "Maya", "age": 16, "grade": "A"}

# Show all students

print("\n--- All Students ---")

for sid, data in database.items():

    print(sid, "-", data["name"], "-", data["grade"])
πŸ‘† Output:
Name : Sara
Age : 17
Grade: B

--- All Students ---
S001 - Ali - A
S002 - Sara - B
S003 - John - A+
S004 - Maya - A
Section 16
Advantages & Disadvantages
✅ Advantages:
Fast lookup — access values by key instantly
Readable — named keys make code self-documenting
Flexible — values can be any data type
Mutable — easily add, update, remove items
Nested — can represent complex data structures
❌ Disadvantages:
No indexing — cannot access by position number
Keys must be unique — duplicate keys overwrite values
More memory — uses more memory than a list
Keys immutable only — lists cannot be dictionary keys
Section 17
Common Mistakes Beginners Make
❌ Mistake 1 — Duplicate key (last wins):
Python
d = {"a": 1, "a": 2}

print(d)   # {'a': 2} ← first 'a' overwritten
❌ Mistake 2 — KeyError when accessing missing key:
Python
d = {"name": "Ali"}

print(d["age"])   # KeyError!

# Fix: use d.get("age") or check first
❌ Mistake 3 — Using mutable key:
Python
d = {[1, 2]: "value"}  # TypeError!

# Fix: use tuple as key → (1,2): "value"
❌ Mistake 4 — Wrong copy method:
Python
d1 = {"a": 1}

d2 = d1          # ← not a copy! reference!

# Fix: d2 = d1.copy()
🌟 Final Tip: Always use get() to access values, copy() to copy, and in to check keys before accessing them.
Python Dictionary key-value dict() Beginner
Python Dictionaries — Store Data with Keys and Values!

Comments