Slide 1
Slide 1
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"}
python
students = {
"Alice": {"age": 25, "grade": "A"},
"Bob": {"age": 22, "grade": "B"},
}
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**
---
- **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}
```
```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"]}
```
---