Python Dictionary: Complete Master Notes & Practical Projects

Master Python Dictionaries from basic key-value data structures, accessing techniques, updating, removing data, dictionary methods (keys, values, items), dynamic user input, to real-life billing systems and practical projects.

1. What is a Dictionary in Python?

English Definition

A Dictionary is a built-in Python data structure that stores data in Key-Value pairs. Keys must be unique and immutable (strings, numbers, tuples), while values can be of any data type and can be duplicated.

Hinglish Explanation

Dictionary Python mein ek data structure hai jisme data Key aur Value ke pair mein store hota hai. Jaise: name → Ali, age → 20, course → Python.

2. Creating a Dictionary

Dictionaries are defined using curly brackets {} with colon : separating keys and values.

Python Code - Creating a Dictionary
student = {
    "name": "Ali",
    "age": 20,
    "course": "Python"
}

print("Student Dictionary:", student)
print("Type:", type(student))
Output
Student Dictionary: {'name': 'Ali', 'age': 20, 'course': 'Python'}
Type: <class 'dict'>

3. Accessing Dictionary Values

Square Bracket vs get() Method

dict[key]: Directly retrieves value. Raises a KeyError if key is missing.

dict.get(key, default): Safely retrieves value. Returns None or a default fallback if key is missing.

Hinglish Explanation

Dictionary mein values keys se access hoti hain. student["name"] direct value nikalta hai, jabki get() method bina error diye value access karta hai.

Python Code - Accessing Keys
student = {
    "name": "Ali",
    "age": 20,
    "course": "Python"
}

print("Name:", student["name"])
print("Age:", student["age"])

print("Course using get():", student.get("course"))
print("Missing Key using get():", student.get("city", "Not Available"))
Output
Name: Ali
Age: 20
Course using get(): Python
Missing Key using get(): Not Available

4. Adding New Data & Updating Values

Assigning a value to a new key creates the key-value pair. Assigning to an existing key updates its value.

Python Code - Adding & Replacing Values
student = {
    "name": "Ali",
    "age": 20
}

student["city"] = "Delhi"
print("After adding city:", student)

student["age"] = 22
print("After updating age:", student)

student["name"] = "Aman"
print("After updating name:", student)
Output
After adding city: {'name': 'Ali', 'age': 20, 'city': 'Delhi'}
After updating age: {'name': 'Ali', 'age': 22, 'city': 'Delhi'}
After updating name: {'name': 'Aman', 'age': 22, 'city': 'Delhi'}

5. Removing Data (pop, popitem, del, clear)

Method / Keyword Syntax Behavior
pop() dict.pop("key") Removes the specified key and returns its value.
popitem() dict.popitem() Removes and returns the last inserted key-value tuple.
del del dict["key"] Deletes specified key or the entire dictionary variable.
clear() dict.clear() Removes all items, leaving an empty dictionary {}.
Python Code - Removing Data
student = {
    "name": "Ali",
    "age": 20,
    "course": "Python",
    "city": "Delhi"
}

removed_age = student.pop("age")
print("Popped Age:", removed_age)
print("Dictionary after pop('age'):", student)

last_item = student.popitem()
print("Popped Last Item:", last_item)

student.clear()
print("Dictionary after clear():", student)
Output
Popped Age: 20
Dictionary after pop('age'): {'name': 'Ali', 'course': 'Python', 'city': 'Delhi'}
Popped Last Item: ('city', 'Delhi')
Dictionary after clear(): {}

6. Length of a Dictionary

len(dict) returns the total count of key-value pairs stored inside the dictionary.

Python Code - len() Method
student = {
    "name": "Ali",
    "age": 20,
    "course": "Python"
}

print("Total Key-Value pairs (len):", len(student))
Output
Total Key-Value pairs (len): 3

7. Looping Through a Dictionary

3 Ways to Iterate

  1. For Loop over Dict: Iterates over keys by default.
  2. Using dict[key] or .values(): Iterates over values.
  3. Using .items(): Iterates over key and value pairs simultaneously.

Hinglish Explanation

Dictionary mein loop lagane ke 3 tarike hain: sirf keys print karwana, keys ke through values nikalna student[key], ya phir .items() se key aur value dono ek sath nikalna.

Python Code - Loops in Dictionary
student = {
    "name": "Ali",
    "age": 20,
    "course": "Python"
}

print("--- Printing Keys ---")
for k in student:
    print("Key:", k)

print("
--- Printing Values ---")
for k in student:
    print("Value:", student[k])

print("
--- Printing Key-Value Pairs (.items) ---")
for k, v in student.items():
    print(k, "->", v)
Output
--- Printing Keys ---
Key: name
Key: age
Key: course

--- Printing Values ---
Value: Ali
Value: 20
Value: Python

--- Printing Key-Value Pairs (.items) ---
name -> Ali
age -> 20
course -> Python

8. Core Dictionary Methods (keys, values, items, update)

Python Code - Dictionary Methods
student = {
    "name": "Ali",
    "age": 20
}

print("Keys view:", student.keys())
print("Values view:", student.values())
print("Items view:", student.items())

student.update({"age": 22, "city": "Delhi"})
print("After update():", student)
Output
Keys view: dict_keys(['name', 'age'])
Values view: dict_values(['Ali', 20])
Items view: dict_items([('name', 'Ali'), ('age', 20)])
After update(): {'name': 'Ali', 'age': 22, 'city': 'Delhi'}

9. Important Dictionary Methods Summary

Method Work / Description
keys() Returns a view object containing all dictionary keys.
values() Returns a view object containing all dictionary values.
items() Returns a view object of key-value tuple pairs.
get(key, default) Safely returns value of key without throwing KeyError.
pop(key) Removes element with specified key and returns its value.
popitem() Removes and returns the last inserted key-value pair.
update(dict2) Updates existing keys or inserts new key-value pairs.
clear() Empties the dictionary completely.

10. Dynamic Dictionary Creation & User Inputs

Creating empty dictionaries dict = {} and dynamically inserting keys and values based on user input or program logic.

Python Code - Dynamic Key Value Addition
student_data = {}

key = "name"
val = "Aman"
student_data[key] = val

key2 = "age"
val2 = 21
student_data[key2] = val2

print("Dynamic Dictionary:", student_data)
Output
Dynamic Dictionary: {'name': 'Aman', 'age': 21}

11. Real-Life Projects & Practical Billing Systems

Project 1: Product Invoice Billing & Discount System

Python Code - Product Billing System
product = "Laptop"
price = 1200.0
quantity = 2

total = price * quantity
discount = total * 0.10 if total > 1000 else 0.0
final_amount = total - discount

invoice = {
    "product": product,
    "original_amount": total,
    "discount": discount,
    "final_amount": final_amount
}

print("=== INVOICE DETAILS ===")
for k, v in invoice.items():
    print(k.replace('_', ' ').title(), ":", v)
Output
=== INVOICE DETAILS ===
Product : Laptop
Original Amount : 2400.0
Discount : 240.0
Final Amount : 2160.0

12. Step-by-Step Practice Code Solutions

Python Code - Practice Solutions
d = {"name": "Ali", "age": 20, "course": "Python"}

print("1. Keys:", list(d.keys()))
print("2. Values:", list(d.values()))
print("3. Name access:", d["name"])

d["city"] = "Delhi"
print("4. Added City:", d)

d["age"] = 22
print("5. Updated Age:", d)

popped = d.pop("course")
print("6. Popped Course:", popped)
print("7. Length:", len(d))

d.clear()
print("8. Cleared:", d)
Output
1. Keys: ['name', 'age', 'course']
2. Values: ['Ali', 20, 'Python']
3. Name access: Ali
4. Added City: {'name': 'Ali', 'age': 20, 'course': 'Python', 'city': 'Delhi'}
5. Updated Age: {'name': 'Ali', 'age': 22, 'course': 'Python', 'city': 'Delhi'}
6. Popped Course: Python
7. Length: 3
8. Cleared: {}