Skip to content

Commit 8d05d72

Browse files
committed
βž• added notes IITM 🐍 🏫
1 parent 194be63 commit 8d05d72

11 files changed

Lines changed: 2054 additions & 2 deletions

β€Žcontent/notes/iit-madras/data-science-and-application/foundational-level/python/_index.mdβ€Ž

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ cascade:
88
series: ["Programming-in-Python"]
99
image: "/images/svg/dark-code.svg"
1010
keywords: ["Python","Programming","Notes","IITM"]
11-
1211
---
1312

1413
{{< hextra/hero-subtitle style="margin:.3rem 0 2rem 0">}}

β€Žcontent/notes/iit-madras/data-science-and-application/foundational-level/python/week 5/Lec1-Dictionaries.mdβ€Ž

Lines changed: 264 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,267 @@
22
title: Dictionaries
33
date: 2025-05-08
44
weight: 51
5-
---
5+
---
6+
7+
Let’s dive into **Dictionaries in Python** πŸ—οΈπŸ“š with clear explanations, emojis, and practice questions (with solutions)!
8+
9+
## What is a Dictionary? πŸ€”
10+
11+
A **dictionary** in Python is a **mutable** (changeable) data structure that stores data as **key-value pairs**. Think of it like a real dictionary: you look up a word (key) to get its definition (value)[^1][^2].
12+
13+
- **Keys**: Must be unique and hashable (like strings, numbers, or tuples of immutables).
14+
- **Values**: Can be any data type (even lists or other dictionaries).
15+
- **Syntax**: Curly braces `{}` and colon `:` separate keys and values.
16+
17+
```python
18+
# Example dictionary
19+
student = {
20+
"name": "Alice",
21+
"age": 20,
22+
"major": "CS"
23+
}
24+
```
25+
26+
πŸ“ *Here, "name", "age", and "major" are keys; "Alice", 20, and "CS" are values.*
27+
28+
## Key Features of Dictionaries πŸ†
29+
30+
- **Unordered**: Items are not stored in a specific order (though Python 3.7+ preserves insertion order).
31+
- **Mutable**: You can add, change, or remove items after creation.
32+
- **No Duplicate Keys**: Each key must be unique. If you assign a value to an existing key, it will overwrite the old value[^2].
33+
- **Fast Lookups**: Accessing a value by key is very quick.
34+
35+
36+
## Creating Dictionaries πŸ› οΈ
37+
38+
**Empty dictionary:**
39+
40+
```python
41+
my_dict = {}
42+
# or
43+
my_dict = dict()
44+
```
45+
46+
**With initial values:**
47+
48+
```python
49+
person = {"name": "Bob", "age": 25}
50+
```
51+
52+
**From a list of tuples:**
53+
54+
```python
55+
pairs = [("a", 1), ("b", 2)]
56+
my_dict = dict(pairs)
57+
```
58+
59+
60+
## Accessing Items πŸ”Ž
61+
62+
- **By key:**
63+
64+
```python
65+
print(person["name"]) # Output: Bob
66+
```
67+
68+
If the key doesn’t exist, you get a `KeyError`.
69+
- **Using `.get()` method:**
70+
71+
```python
72+
print(person.get("age")) # Output: 25
73+
print(person.get("height", 0)) # Output: 0 (default value)
74+
```
75+
76+
Safer, as it returns `None` or a default value if the key is missing[^2].
77+
78+
79+
## Modifying Dictionaries ✏️
80+
81+
**Add or update a key-value pair:**
82+
83+
```python
84+
person["city"] = "Delhi" # Adds a new key
85+
person["age"] = 26 # Updates existing key
86+
```
87+
88+
**Remove an item:**
89+
90+
```python
91+
del person["city"] # Removes key 'city'
92+
removed = person.pop("age") # Removes 'age' and returns its value
93+
```
94+
95+
96+
## Dictionary Methods πŸ› οΈ
97+
98+
| Method | Description | Example |
99+
| :-- | :-- | :-- |
100+
| `.keys()` | Returns all keys | `person.keys()` |
101+
| `.values()` | Returns all values | `person.values()` |
102+
| `.items()` | Returns all key-value pairs (tuples) | `person.items()` |
103+
| `.update()` | Updates dictionary with another dict | `person.update({"age": 27})` |
104+
| `.get()` | Gets value for key (safe) | `person.get("age", 0)` |
105+
| `.pop()` | Removes key and returns its value | `person.pop("age")` |
106+
107+
## Looping Through Dictionaries πŸ”„
108+
109+
**Loop through keys:**
110+
111+
```python
112+
for key in person:
113+
print(key)
114+
```
115+
116+
**Loop through values:**
117+
118+
```python
119+
for value in person.values():
120+
print(value)
121+
```
122+
123+
**Loop through key-value pairs:**
124+
125+
```python
126+
for key, value in person.items():
127+
print(f"{key}: {value}")
128+
```
129+
130+
131+
## Practice Questions with Solutions πŸ‹οΈβ€β™‚οΈ
132+
133+
### 1. Create a dictionary with your name, age, and city. Print each value.
134+
135+
```python
136+
my_info = {"name": "Rahul", "age": 21, "city": "Mumbai"}
137+
print(my_info["name"]) # Rahul
138+
print(my_info["age"]) # 21
139+
print(my_info["city"]) # Mumbai
140+
```
141+
142+
143+
### 2. Add a new key "country" with value "India" to your dictionary. Then, remove the "city" key.
144+
145+
```python
146+
my_info["country"] = "India"
147+
del my_info["city"]
148+
print(my_info) # {'name': 'Rahul', 'age': 21, 'country': 'India'}
149+
```
150+
151+
152+
### 3. Given the dictionary: `fruits = {"apple": 2, "banana": 3, "orange": 1}`
153+
154+
Write code to:
155+
156+
- Print all keys
157+
- Print all values
158+
- Print all key-value pairs
159+
160+
```python
161+
fruits = {"apple": 2, "banana": 3, "orange": 1}
162+
print(fruits.keys()) # dict_keys(['apple', 'banana', 'orange'])
163+
print(fruits.values()) # dict_values([2, 3, 1])
164+
print(fruits.items()) # dict_items([('apple', 2), ('banana', 3), ('orange', 1)])
165+
```
166+
167+
168+
### 4. Write a function that counts the frequency of each letter in a string and returns a dictionary.
169+
170+
```python
171+
def letter_count(s):
172+
freq = {}
173+
for char in s:
174+
if char in freq:
175+
freq[char] += 1
176+
else:
177+
freq[char] = 1
178+
return freq
179+
180+
print(letter_count("banana")) # {'b': 1, 'a': 3, 'n': 2}
181+
```
182+
183+
184+
### 5. Check if "apple" is a key in the `fruits` dictionary.
185+
186+
```python
187+
if "apple" in fruits:
188+
print("Yes, apple is in the dictionary!")
189+
else:
190+
print("No, apple is not found.")
191+
```
192+
193+
194+
## Step-by-Step Example: Counting Unique Characters
195+
196+
**Problem:** Count the number of unique characters in a string using a dictionary.
197+
198+
**Step 1:** Create an empty dictionary
199+
**Step 2:** Loop through each character in the string
200+
**Step 3:** If character is not in dictionary, add it
201+
**Step 4:** Print the length of the dictionary (number of unique characters)
202+
203+
```python
204+
s = "hello world"
205+
unique_chars = {}
206+
for char in s:
207+
unique_chars[char] = 1 # Value doesn't matter here
208+
print(len(unique_chars)) # Output: 8 (h, e, l, o, , w, r, d)
209+
```
210+
211+
212+
## Common Pitfalls ⚠️
213+
214+
- **Keys must be hashable**: You can't use lists or other dictionaries as keys.
215+
- **Accessing a missing key with `[]` raises KeyError**: Use `.get()` to avoid errors.
216+
- **Duplicate keys are not allowed**: The last value assigned to a key will overwrite previous ones.
217+
218+
219+
## Dictionary Comprehensions 🧠
220+
221+
You can create dictionaries in a single line using a comprehension:
222+
223+
```python
224+
squares = {x: x*x for x in range(1, 6)}
225+
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
226+
```
227+
228+
229+
## Summary Table: Lists vs Dictionaries
230+
231+
| Feature | List | Dictionary |
232+
| :-- | :-- | :-- |
233+
| Access by | Index (position) | Key (any hashable object) |
234+
| Syntax | `[^1][^3][^2]` | `{"a": 1, "b": 2}` |
235+
| Mutable | Yes | Yes |
236+
| Ordered | Yes (since Python 3.7) | Yes (since Python 3.7) |
237+
| Duplicate keys? | N/A | No |
238+
239+
## Try It Yourself! πŸš€
240+
241+
**Q:** Create a dictionary for three students with their names as keys and their grades as values. Then, print the average grade.
242+
243+
**Solution:**
244+
245+
```python
246+
grades = {"Anil": 85, "Bina": 92, "Chetan": 78}
247+
average = sum(grades.values()) / len(grades)
248+
print(f"Average grade: {average}")
249+
```
250+
251+
**Dictionaries** are super useful for organizing and accessing data quickly by a unique key! Practice using them in your projects and you'll master them in no time! πŸ˜ƒπŸ”‘[^1][^3][^2]
252+
253+
<div style="text-align: center">⁂</div>
254+
255+
[^1]: itpacs_cafiero.pdf
256+
257+
[^2]: Introduction_to_Python_Programming_-_WEB.pdf
258+
259+
[^3]: Learning_Python.pdf
260+
261+
[^4]: thinkpython2.pdf
262+
263+
[^5]: Python-Cheatsheet-2024.pdf
264+
265+
[^6]: OER-202301_Wang_2023-Introduction-to-Computer-Programming-with-Python.pdf
266+
267+
[^7]: pythonlearn.pdf
268+

0 commit comments

Comments
Β (0)