Dictionaries (Easy Words)
• A dictionary stores data as key : value pairs.
• It is like a list, but:
o Lists use numbers as indexes
o Dictionaries use keys (can be strings, numbers, etc.)
Creating a Dictionary
eng2sp = {}
• {} means an empty dictionary
Or using dict():
eng2sp = dict()
Adding Items
eng2sp['one'] = 'uno'
• 'one' → key
• 'uno' → value
Dictionary with Multiple Items
eng2sp = {'one':'uno', 'two':'dos', 'three':'tres'}
Accessing Values
eng2sp['two']
• Output: 'dos'
Important Points
• Order does not matter when looking up values
• If key is not found → KeyError
Useful Functions
len()
len(eng2sp)
• Returns number of key–value pairs
Using in Operator
• Checks keys only
'one' in eng2sp # True
'uno' in eng2sp # False
Checking Values
'uno' in [Link]()
• True if value exists
Why Dictionaries Are Fast
• Dictionaries use hash tables
• Searching is very fast, even for big dictionaries
Dictionary as Counters (Easy Words)
Problem
• Count how many times each letter appears in a word.
Best Solution: Use a Dictionary
• Key → letter
• Value → count of that letter
Basic Counting Logic
word = "brontosaurus"
d = {}
for c in word:
if c not in d:
d[c] = 1
else:
d[c] += 1
• First time letter appears → set count to 1
• Next time → increase count
DECTIONARY COUNTER
Result Example
{'b':1, 'r':2, 'o':2, 'n':1, 't':1, 's':2, 'a':1, 'u':2}
• This result is called a histogram
• Histogram = frequency count
Using get() (Shorter & Better Way)
• get(key, default):
o Returns value if key exists
o Returns default if key doesn’t exist
d[c] = [Link](c, 0) + 1
Full Short Code
word = "brontosaurus"
d = {}
for c in word:
d[c] = [Link](c, 0) + 1
print(d)
Dictionaries and Files (Easy Words)
Goal
• Count how many times each word appears in a text file.
How the Program Works
1. Ask for file name
fname = input("Enter the file name:")
2. Open the file
• If file doesn’t exist → show error and stop.
3. Create empty dictionary
counts = {}
• Stores:
• word → count
4. Read file line by line (Outer loop)
for line in fhand:
5. Split line into words
words = [Link]()
6. Count each word (Inner loop)
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
Important Concepts
• Nested loops:
o Outer loop → lines
o Inner loop → words in each line
• Ensures every word is counted
Example Output
{'But':1, 'soft':1, 'what':1, 'the':3, 'and':3, ...}
• Dictionary is unordered
• Shows word frequency
Shortcut Operator
• counts[word] += 1
• Same as:
counts[word] = counts[word] + 1
Looping and Dictionaries (Easy Words)
Looping Through a Dictionary
• When you use a for loop on a dictionary, it loops through the keys.
for key in counts:
print(key, counts[key])
• key → dictionary key
• counts[key] → value of that key
Example Output
chuck 1
annie 42
jan 100
Printing Only Certain Values
• To print items with value greater than 10:
for key in counts:
if counts[key] > 10:
print(key, counts[key])
• Output:
annie 42
jan 100
Printing Keys in Alphabetical Order
1. Get all keys as a list:
lst = list([Link]())
2. Sort the list:
[Link]()
3. Loop through sorted keys:
for key in lst:
print(key, counts[key])
Output
annie 42
chuck 1
jan 100
Important Points
• Dictionaries loop over keys
• Use counts[key] to get values
• Sorting requires converting keys to a list
Classes and Methods (Easy Words)
Object-Oriented Programming (OOP)
• Python is an object-oriented language.
• Programs are built using classes and objects.
• Objects represent real-world things.
• Methods represent actions of those things.
Class
• A class is a blueprint to create objects.
• Objects created from a class share the same structure.
__init__ Method (Initializer)
• __init__ runs automatically when an object is created.
• It sets the initial values of the object.
def __init__(self, hour=0, minute=0, second=0):
[Link] = hour
[Link] = minute
[Link] = second
• self refers to the current object.
__str__ Method
• __str__ tells Python how to display an object as a string.
• It runs when you use print().
def __str__(self):
return "%02d:%02d:%02d" % ([Link], [Link], [Link])
Example
time = Time(9, 45)
print(time)
• Output:
09:45:00
Operator Overloading (Easy Words)
• Operator overloading means giving new meaning to operators like + for your own
classes.
• In Python, this is done using special methods.
Using + with Objects
• Define the __add__() method in a class.
• Python calls __add__() when you use +.
def __add__(self, other):
...
Example (Time Class)
start = Time(9, 45)
duration = Time(1, 35)
print(start + duration)
• Output:
11:20:00
• + → calls __add__
• print() → calls __str__
Type-Based Dispatch
• Sometimes, you want + to work with different types.
• Example:
o Time + Time
o Time + int
TYPE BASED DISPACTH -How Python Decides
• Use isinstance() to check the type.
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return [Link](other)
Example Results
start + duration # Time + Time → OK
start + 1337 # Time + int → OK
1337 + start # int + Time → ERROR
Why Error Happens
• Python looks for __add__ in the left operand.
• int doesn’t know how to add Time.
Key Points
• __add__ controls +
• __str__ controls printing
• isinstance() checks type
• Type-based dispatch chooses method based on type
Polymorphism
Type-based dispatch is useful when it is necessary, but (fortunately) it is not always neces-
sary. Often you can avoid it by writing functions that work correctly for arguments with
different types. Many of the functions we wrote for strings also work for other sequence
types. For exam- ple, in Section 11.2 we used histogram to count the number of times each
letter appears in a word.