LEARN COMPLETE PYTHON IN 24 HOURS

10. Dictionaries

A dictionary (or dict) is an unordered, mutable, and indexed collection of key-value pairs. Keys must be unique and immutable (strings, numbers, tuples), values can be anything.

10.1 Creating & Accessing Dictionaries

Ways to create a dictionary:

  1. Empty dictionary

Python

my_dict = {} empty = dict() # same thing

  1. With key-value pairs

Python

person = { "name": "Anshuman", "age": 25, "city": "Muzaffarpur", "is_student": True, "hobbies": ["coding", "cricket", "reading"] } student = dict(name="Rahul", marks=85, grade="A")

Accessing values Use square brackets [] with key (fast & common)

Python

print(person["name"]) # Anshuman print(person["age"]) # 25 print(person["hobbies"]) # ['coding', 'cricket', 'reading']

Safer way: .get() method (returns None if key not found, no error)

Python

print(person.get("phone")) # None print(person.get("phone", "Not available")) # Not available

Tip: Never use [] if key might not exist → it raises KeyError.

10.2 Adding, Updating, Removing Items

Dictionaries are mutable — easy to change.

  1. Add or Update (same syntax)

Python

person["phone"] = "9876543210" # adds new key person["age"] = 26 # updates existing person["skills"] = ["Python", "HTML"] # adds list print(person["phone"]) # 9876543210

  1. Remove item

Python

del person["is_student"] # removes key-value pair removed_age = person.pop("age") # removes & returns value print(removed_age) # 26 person.pop("city", None) # safe remove (no error if missing)

  1. Clear entire dictionary

Python

person.clear() # becomes {}

Tip: Use pop() when you want the removed value, del when you don't.

10.3 Dictionary Methods (keys, values, items, get, update, pop, etc.)

Important built-in methods:

MethodDescriptionExampleResult / Returnskeys()Returns all keysperson.keys()dict_keys(['name', 'age', ...])values()Returns all valuesperson.values()dict_values(['Anshuman', 25, ...])items()Returns key-value pairs as tuplesperson.items()dict_items([('name', 'Anshuman'), ...])get(key, default)Get value safely (default if missing)person.get("age", 0)25 or 0update()Merge another dict or add multiple pairsperson.update({"city": "Patna", "job": "Dev"})Updates personpop(key)Remove & return valueperson.pop("name")'Anshuman'popitem()Remove & return last inserted pair (Python 3.7+)person.popitem()('job', 'Dev')clear()Remove all itemsperson.clear(){}copy()Shallow copy of dictionarynew = person.copy()New independent dict

Practical Example – Update & Merge

Python

info = {"name": "Priya", "age": 22} extra = {"city": "Delhi", "skills": ["Java", "SQL"]} info.update(extra) print(info) # {'name': 'Priya', 'age': 22, 'city': 'Delhi', 'skills': ['Java', 'SQL']}

10.4 Looping through Dictionaries

Three main ways:

  1. Loop over keys (default)

Python

for key in person: print(key, ":", person[key])

  1. Loop over keys() explicitly

Python

for key in person.keys(): print(key)

  1. Loop over values

Python

for value in person.values(): print(value)

  1. Loop over key-value pairs (best & most common)

Python

for key, value in person.items(): print(f"{key.capitalize()}: {value}")

Output example:

text

Name: Anshuman Age: 25 City: Muzaffarpur Hobbies: ['coding', 'cricket', 'reading']

Tip: Always prefer .items() when you need both key and value.

10.5 Nested Dictionaries

Dictionaries inside dictionaries — very useful for complex data (like JSON, student records, configs).

Example – Student Database

Python

students = { "student1": { "name": "Anshuman", "age": 25, "marks": {"math": 95, "science": 88, "english": 92}, "address": {"city": "Muzaffarpur", "state": "Bihar"} }, "student2": { "name": "Rahul", "age": 24, "marks": {"math": 78, "science": 85}, "address": {"city": "Patna"} } } # Access nested data print(students["student1"]["name"]) # Anshuman print(students["student1"]["marks"]["math"]) # 95 print(students["student2"]["address"].get("state", "N/A")) # N/A # Update nested students["student1"]["marks"]["science"] = 90 # Add new student students["student3"] = {"name": "Priya", "age": 23}

Loop through nested dictionary

Python

for student_id, details in students.items(): print(f"\nStudent ID: {student_id}") for key, value in details.items(): if isinstance(value, dict): print(f" {key.capitalize()}:") for sub_key, sub_value in value.items(): print(f" {sub_key}: {sub_value}") else: print(f" {key.capitalize()}: {value}")

Mini Project – Simple Contact Book

Python

contacts = {} while True: print("\n1. Add Contact 2. View Contact 3. Delete Contact 4. Exit") choice = input("Choose: ") if choice == "1": name = input("Name: ").strip().title() phone = input("Phone: ").strip() contacts[name] = phone print(f"{name} added!") elif choice == "2": name = input("Enter name to search: ").strip().title() if name in contacts: print(f"{name}: {contacts[name]}") else: print("Not found!") elif choice == "3": name = input("Enter name to delete: ").strip().title() contacts.pop(name, None) print("Deleted if existed.") elif choice == "4": print("Goodbye!") break

This completes the full Dictionaries section — now you can handle key-value data like a pro!