INTRODUCTION TO DICTIONARIES IN PYTHON
Title: What are Dictionaries in Python?
Definition:
A dictionary in Python is a built-in data structure that stores
data as key-value pairs. It is mutable, unordered (as of Python
3.7+ insertion order is preserved), and highly efficient for
lookups.
Key Characteristics:
- Keys must be unique and immutable (e.g., strings, numbers,
tuples).
- Values can be of any type (e.g., integers, strings, lists, even
other dictionaries).
- Dictionaries are dynamic, meaning they can grow or shrink as
needed.
Why Use Dictionaries?
- Fast access to values using keys.
- Useful for representing structured data like JSON,
configuration settings, etc.
Illustration:
PLAINTEXT
+-------------------+
| Dictionary |
| |
| Key Value |
| "name" -> "Alice" |
| "age" -> 25 |
| "city" -> "NYC" |
+-------------------+
Slide 2: Creating and Accessing Dictionaries
Title: How to Create and Access Dictionaries
Creating a Dictionary:
Dictionaries can be created using curly braces `{}` or the
`dict()` constructor.
python
# Using curly braces
my_dict = {"name": "Alice", "age": 25, "city": "NYC"}
Using dict() constructor
my_dict = dict(name="Alice", age=25, city="NYC")
Accessing Values:
Use the key inside square brackets `[]` or the `.get()` method.
python
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 25
Handling Missing Keys:
If a key doesn’t exist, accessing it with `[]` raises a `KeyError`.
The `.get()` method avoids this by returning `None` or a default
value.
python
print(my_dict.get("country", "USA")) # Output: USA
Illustration:
PLAINTEXT
my_dict = {"name": "Alice", "age": 25}
| | |
Key Value Key
Slide 3: Modifying and Updating Dictionaries
Title: Adding, Updating, and Deleting Items
Adding or Updating Items:
Assign a value to a new or existing key.
python
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "NYC" # Add a new key-value pair
my_dict["age"] = 26 # Update an existing key
Deleting Items:
Use `del`, `.pop()`, or `.clear()`.
python
del my_dict["city"] # Deletes the "city" key
age = my_dict.pop("age") # Removes and returns the value
of "age"
my_dict.clear() # Clears all items in the dictionary
Iterating Over a Dictionary:
You can loop through keys, values, or key-value pairs.
python
for key in my_dict:
print(key) # Prints keys
for value in my_dict.values():
print(value) # Prints values
for key, value in my_dict.items():
print(f"{key}: {value}") # Prints key-value pairs
Illustration:
plaintext
Before: {"name": "Alice", "age": 25}
After Adding: {"name": "Alice", "age": 25, "city": "NYC"}
After Deleting: {"name": "Alice", "age": 25}
SLIDE 4: NESTED DICTIONARIES
Title: Working with Nested Dictionaries
What Are Nested Dictionaries?
A nested dictionary is a dictionary that contains another
dictionary as its value.
python
students = {
"Alice": {"age": 25, "grade": "A"},
"Bob": {"age": 22, "grade": "B"},
}
Accessing Nested Values:
Use multiple keys to access nested values.
python
print(students["Alice"]["grade"]) # Output: A
Modifying Nested Values:
Update values within nested dictionaries.
python
students["Alice"]["grade"] = "A+"
Use Case:
Nested dictionaries are ideal for hierarchical data structures,
such as user profiles, organizational charts, etc.
Illustration:
plaintext
students = {
"Alice": {"age": 25, "grade": "A"},
"Bob": {"age": 22, "grade": "B"},
}
| | |
Key Key Value
SLIDE 5: DICTIONARY METHODS
Title: Common Dictionary Methods
View Methods:
- `.keys()`: Returns a view object of all keys.
- `.values()`: Returns a view object of all values.
- `.items()`: Returns a view object of key-value pairs.
python
my_dict = {"name": "Alice", "age": 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
print(my_dict.values()) # Output: dict_values(['Alice', 25])
print(my_dict.items()) # Output: dict_items([('name', 'Alice'),
('age', 25)])
Other Useful Methods:
- `.update()`: Adds key-value pairs from another dictionary.
- `.setdefault()`: Returns the value of a key, or sets a default if
the key doesn’t exist.
- `.copy()`: Creates a shallow copy of the dictionary.
python
my_dict.update({"city": "NYC"})
print(my_dict.setdefault("country", "USA")) # Output: USA
Illustration:
plaintext
my_dict = {"name": "Alice", "age": 25}
my_dict.update({"city": "NYC"})
Result: {"name": "Alice", "age": 25, "city": "NYC"}
### **Slide 6: Applications of Dictionaries**
---
**Title:** Real-World Applications of Dictionaries
- **Data Representation:**
Dictionaries are widely used to represent JSON-like data
structures, making them ideal for APIs and web development.
- **Counting Frequencies:**
Use dictionaries to count occurrences of elements in a list.
```python
words = ["apple", "banana", "apple", "orange"]
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # Output: {'apple': 2, 'banana': 1, 'orange':
1}
```
- **Configuration Settings:**
Store application settings or configurations in dictionaries.
```python
config = {"theme": "dark", "language": "en", "notifications":
True}
```
- **Graphs and Maps:**
Represent graphs or adjacency lists using dictionaries.
```python
graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A"]}
```
**Illustration:**
```plaintext
Real-world Use Cases:
- JSON Data: {"name": "Alice", "age": 25}
- Word Count: {"apple": 2, "banana": 1}
- Graph: {"A": ["B", "C"]}
```
---
### **Final Notes:**
Dictionaries are one of the most versatile and powerful data
structures in Python. Mastering their usage will significantly
enhance your programming skills!