Learn Python Dictionaries: Complete Guide with Examples
π Python Dictionaries
Complete Guide
Keys · Values · Methods · Nested · Looping · Real-Life Project
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.
student = { "name" : "Ali", "age" : 18, "grade" : "A" } print(student)
| Feature | Description |
|---|---|
| key-value pairs | Each item has a key and a value |
| Unique keys | No two items can have the same key |
| Mutable | Can add, change, remove items |
| Ordered | Items keep insertion order (Python 3.7+) |
| Keys immutable | Keys must be str, int, or tuple |
| Values any type | Values can be any data type |
| No index | Access via key, not position number |
# 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}
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.
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
dict["key"].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.
student = {"name": "Ali", "age": 18} # Add one item student["grade"] = "A" # Add multiple using update() student.update({"city": "Karachi", "score": 95}) print(student)
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.
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)
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.
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("key", None) to avoid the error.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.
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)
age : 18
grade : A
| Method | Description |
|---|---|
| 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 |
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)...])
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.
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"])
students = [ {"name": "Ali", "grade": "A"}, {"name": "Sara", "grade": "B"}, {"name": "John", "grade": "A+"} ] for s in students: print(s["name"], "-", s["grade"])
Sara - B
John - A+
marks = { "Ali": [85, 90, 78], "Sara": [92, 88, 95] } print(sum(marks["Ali"])) # 253 print(max(marks["Sara"])) # 95
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.
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
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.
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")
Has 3 items
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.
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
value in dict.values()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.
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"])
Age : 17
Grade: B
--- All Students ---
S001 - Ali - A
S002 - Sara - B
S003 - John - A+
S004 - Maya - A
d = {"a": 1, "a": 2} print(d) # {'a': 2} ← first 'a' overwritten
d = {"name": "Ali"} print(d["age"]) # KeyError! # Fix: use d.get("age") or check first
d = {[1, 2]: "value"} # TypeError! # Fix: use tuple as key → (1,2): "value"
d1 = {"a": 1} d2 = d1 # ← not a copy! reference! # Fix: d2 = d1.copy()
get() to access values, copy() to copy, and in to check keys before accessing them.
Comments
Post a Comment