Lesson 5.4: Dictionaries – Key-Value Pairs, Methods
Introduction:
Dictionaries are unordered collections of key-value pairs in Python. They allow you to store data in a structured way, where each key is unique and maps to a value. Dictionaries are widely used for fast lookups, data organization, and JSON-like data handling.
1. Creating Dictionaries:
-
Dictionaries are created using curly braces
{}with key-value pairs separated by colons:.
Examples:
2. Accessing Values:
-
Access values using keys.
-
Use
get()to safely access values.
Examples:
3. Adding and Modifying Items:
4. Removing Items:
-
pop(key)– Removes and returns the value of the given key -
popitem()– Removes and returns the last inserted key-value pair -
del dict[key]– Deletes a key-value pair -
clear()– Removes all items
Example:
5. Dictionary Methods:
| Method | Description |
|---|---|
keys() |
Returns all keys |
values() |
Returns all values |
items() |
Returns all key-value pairs |
update() |
Updates dictionary with new key-value pairs |
copy() |
Returns a shallow copy of the dictionary |
Example:
Practical Tips:
-
Keys must be unique and immutable (like strings, numbers, tuples)
-
Values can be of any data type
-
Ideal for storing structured data like JSON or configuration data
Learning Outcome of This Lesson:
-
Understand how to create and use dictionaries
-
Access, add, modify, and remove key-value pairs
-
Apply built-in dictionary methods efficiently
-
Use dictionaries for real-world data storage and lookup tasks
