Lesson 10: Dictionaries in Python

๐ŸŽฏ Lesson Objective

To understand how to create, access, and manipulate dictionaries โ€” one of Pythonโ€™s most powerful data structures for storing key-value pairs.


๐Ÿงฉ 1. What Is a Dictionary?

A dictionary is a collection of key-value pairs enclosed in curly braces {}.
Each key is unique, and it is used to access its corresponding value.

โœ… Example:

student = {
    "name": "Sameer",
    "age": 25,
    "city": "Warangal"
}

print(student)

Output:

{'name': 'Sameer', 'age': 25, 'city': 'Warangal'}

โš™๏ธ 2. Accessing Dictionary Elements

You can access values using their keys.

print(student["name"])      # Using key directly
print(student.get("age"))   # Using get() method

Output:

Sameer
25

๐Ÿงฑ 3. Adding and Updating Items

โœ… Add a New Key-Value Pair

student["course"] = "Python"
print(student)

โœ… Update Existing Value

student["age"] = 26
print(student)

Output:

{'name': 'Sameer', 'age': 26, 'city': 'Warangal', 'course': 'Python'}

โŒ 4. Removing Items

MethodDescriptionExample
pop(key)Removes key and returns valuestudent.pop("city")
delDeletes key-value pairdel student["age"]
clear()Removes all itemsstudent.clear()

โœ… Example:

student.pop("city")
print(student)

Output:

{'name': 'Sameer', 'age': 25}

๐Ÿ” 5. Looping Through a Dictionary

โœ… Loop Through Keys:

for key in student:
    print(key)

โœ… Loop Through Values:

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

โœ… Loop Through Both:

for key, value in student.items():
    print(key, ":", value)

Output:

name : Sameer
age : 25
city : Warangal

๐Ÿงฎ 6. Checking for Keys

You can verify if a key exists using the in operator.

if "name" in student:
    print("Name exists!")

Output:

Name exists!

๐Ÿ“ฆ 7. Dictionary Methods

MethodDescriptionExample
keys()Returns all keysstudent.keys()
values()Returns all valuesstudent.values()
items()Returns key-value pairsstudent.items()
copy()Returns a shallow copystudent.copy()
update()Adds or updates multiple itemsstudent.update({"country": "India"})

โœ… Example:

student.update({"country": "India", "language": "English"})
print(student)

Output:

{'name': 'Sameer', 'age': 25, 'city': 'Warangal', 'country': 'India', 'language': 'English'}

๐Ÿ”— 8. Nested Dictionaries

You can store dictionaries inside other dictionaries.

โœ… Example:

students = {
    "s1": {"name": "Ali", "age": 22},
    "s2": {"name": "Sara", "age": 21},
    "s3": {"name": "John", "age": 23}
}

print(students["s2"]["name"])

Output:

Sara

๐Ÿ”„ 9. Dictionary Comprehension

Create a dictionary in one line using comprehension.

โœ… Example:

squares = {x: x*x for x in range(5)}
print(squares)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

๐ŸŒ 10. Real-Life Example โ€“ Contact Book

contacts = {
    "Ali": "9876543210",
    "Sara": "9123456789",
    "John": "9988776655"
}

name = input("Enter name: ")
if name in contacts:
    print(f"{name}'s number is {contacts[name]}")
else:
    print("Contact not found.")

Output:

Enter name: Sara
Sara's number is 9123456789


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *