๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Create and use dictionaries in Python
-
Access, add, update, and remove keyโvalue pairs
-
Use common dictionary methods:
.get()
,.update()
,.pop()
,.keys()
,.values()
,.items()
-
Understand real-world use cases for dictionaries
๐ Lesson Content
๐น What is a Dictionary in Python?
A dictionary is a collection of keyโvalue pairs.
-
Keys must be unique and immutable
-
Values can be of any type
-
Dictionaries are unordered (until Python 3.6) and mutable
Syntax:
๐ธ Accessing Values
โ
If the key doesnโt exist, this will raise a KeyError
.
Use .get()
to avoid errors:
๐ธ Adding or Updating Values
๐ธ Removing Items
๐ธ Dictionary Methods
Method | Description | Example |
---|---|---|
.get(key) |
Returns value or default if not found | student.get("age", 0) |
.update() |
Updates one dictionary with another | student.update({"age": 14}) |
.pop(key) |
Removes key and returns its value | student.pop("grade") |
.keys() |
Returns a view of all keys | student.keys() |
.values() |
Returns a view of all values | student.values() |
.items() |
Returns all keyโvalue pairs | student.items() |
๐ Looping Through a Dictionary
Or:
โ Real-World Use Cases
-
Storing student profiles, product info, API data
-
Working with JSON or external data files
-
Fast lookup using keys
๐ง Mini Practice
๐ Assignment
-
Create a dictionary named
person
with keys:name
,age
,city
. -
Add a new key:
country
with any value. -
Update the
city
. -
Remove the
age
key. -
Loop through and print each key-value pair.