01-12-2024
Module 3
Page 2
Module 3
► SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop.
► SEQUENCE DATA TYPES IN PYTHON - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).
► DECOMPOSITION AND MODULARIZATION* :- Problem decomposition as a strategy for
solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values
Page 3
1
01-12-2024
Python Dictionary
Page 4
What is a Dictionary?
► A dictionary in Python is a built-in data type that allows you to store and manage data in a
structured way using key-value pairs.
► This means each value is associated with a unique key, making it easy to access, update, or
delete specific elements.
► A dictionary is defined by enclosing key-value pairs within curly braces {}, with each key-
value pair separated by a colon : and pairs separated by commas.
Syntax Example
my_dict = { student = {
"key1": "value1", "name": "Alice",
"key2": "value2", "age": 20,
"key3": "value3" "courses": ["Math", "Science"]
} }
Page 4
2
01-12-2024
Characteristics of a Dictionary
► Unordered: Dictionaries do not maintain the order of elements
► Mutable: You can modify the values of a dictionary after creation.
► Key Uniqueness: Each key in a dictionary must be unique. If a duplicate key is added, the
latest value overwrites the previous one.
► Key Type: Keys must be immutable types (e.g., strings, numbers, tuples), but values can be
of any type.
# Defining a dictionary with keys of immutable types: string, number, and tuple
my_dict = {
"name": "Alice", # String key
42: "Answer to everything", # Integer key
(1, 2): "Point" # Tuple key
}
Page 5
Accessing Dictionary Elements
► You can access values in a dictionary by using their corresponding keys
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Science"]
}
print(student["name"]) # Output: Alice
print(student["nam"]) # Output: KeyError: 'nam'
► To avoid errors if a key doesn’t exist, use the .get() method:
print(student.get("age", "Key not found")) # Output: 20
print(student.get("ag", "Key not found")) # Key not found
Page 6
3
01-12-2024
Adding or Updating Elements
► To add a new key-value pair or update an existing key, use the
assignment syntax:
student["age"] = 21 # Updates the age to 21
student["grade"] = "A" # Adds a new key 'grade'
Page 7
Removing Elements
► You can remove elements from a dictionary in multiple ways
► Using del keyword
del student["age"] # Removes the 'age' key-value pair
► Using .pop() method:
student.pop("grade", "Key not found") # Removes 'grade' and returns its value
► Using .popitem(): Removes the last inserted key-value pair in Python 3.7+.
Page 8
4
01-12-2024
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
print(student.get("name")) # Output: Alice
Retrieves value for a specified key; print(student.get("grade", "N/A"))
.get()
returns default if key is not found. # Output: N/A (since "grade" key doesn't exist)
python student = {"name": "Alice", "age": 20}
Returns a view of all keys in the print(student.keys())
.keys() # Output: dict_keys(['name', 'age’])
dictionary.
python student = {"name": "Alice", "age": 20}
Returns a view of all values in the print(student.values())
.values() # Output: dict_values(['Alice', 20])
dictionary.
python student = {"name": "Alice", "age": 20}
Returns a view of all key-value pairs as
.items() print(student.items())
tuples.
# Output: dict_items([('name', 'Alice'), ('age', 20)])
Page 9
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
new_data = {"grade": "A", "age": 21}
Adds or updates multiple key-value pairs from student.update(new_data)
.update() print(student)
another dictionary.
# Output: {'name': 'Alice', 'age': 21, 'grade': 'A’}
python student = {"name": "Alice", "age": 20}
age = student.pop("age")
.pop() Removes a specified key and returns its value. print(age) # Output: 20
print(student) # Output: {'name': 'Alice’}
python student = {"name": "Alice", "age": 20}
Removes and returns the last inserted key- last_item = student.popitem()
.popitem()
value pair. print(last_item) # Output: ('age', 20)
print(student) # Output: {'name': 'Alice'}
Page 10
5
01-12-2024
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
Removes all elements from the student.clear() print(student) # Output: {}
.clear()
dictionary.
python student = {"name": "Alice", "age": 20} student_copy =
student.copy() student_copy["age"] = 21
Creates a shallow* copy of the print(student) # Output: {'name': 'Alice', 'age': 20}
.copy()
dictionary. print(student_copy) # Output: {'name': 'Alice', 'age': 21}
python keys = ["name", "age", "grade"]
default_value = "Not specified"
Creates a new dictionary with
new_dict = dict.fromkeys(keys, default_value)
.fromkeys() specified keys, each assigned to a
print(new_dict)
given value (or None).
# Output: {'name': 'Not specified', 'age': 'Not specified',
'grade': 'Not specified'}
*A shallow copy is a duplicate of an object, but it only copies the references to the elements in the object, not the actual objects themselves. This means
that if the original object contains mutable objects (like lists or dictionaries), both the original and the shallow copy will point to the same objects, so
changes made to mutable elements in one will be reflected in the other.
Page 11
Iterating Through a Dictionary
► You can use loops to iterate over keys, values, or both in a dictionary
► Iterating over keys
for key in student.keys():
print(key)
► Iterating over values
for value in student.values():
print(value)
► Iterating over key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
Page 12
6
01-12-2024
Example Use Case: Counting Word Frequencies
► Dictionaries can contain other dictionaries as values, which is helpful for
representing more complex data.
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # Output: {'apple': 3, 'banana': 2, 'orange': 1}
word_count[word] = word_count.get(word, 0) + 1
• This updates the count for the current word in the word_count dictionary:
• If the word exists in the dictionary, its count is incremented by 1.
• If the word does not exist, it is added to the dictionary with a count of 1.
Page 13
Nested Dictionaries
► Dictionaries can contain other dictionaries as values, which is helpful for
representing more complex data.
students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
Page 14
7
01-12-2024
Exercise
► Create a telephone directory using a dictionary. The name of the individual
and the telephone number will be key and value, respectively. Write a
Python program that allows the user to perform the following operations:
► Add a Contact: Add a new contact with a name and phone number to the directory.
► Update a Contact: Update the phone number of an existing contact.
► Delete a Contact: Remove a contact from the directory.
► Search for a Contact: Look up the phone number of a contact by their name.
► Display All Contacts: Print all contacts in the directory.
► Exit the program.
► Use a menu-driven approach.
Page 15