0% found this document useful (0 votes)
72 views

Module 3.2.4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Module 3.2.4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ALGORITHMIC THINKING WITH PYTHON

Prof. Sarju S
19 November 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 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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

Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 8 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
print(student.get("name")) # Output: Alice
Retrieves value for a specified key;
.get() print(student.get("grade", "N/A"))
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()
dictionary. # Output: dict_keys(['name', 'age’])

python student = {"name": "Alice", "age": 20}


Returns a view of all values in the print(student.values())
.values()
dictionary. # Output: dict_values(['Alice', 20])

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 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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()
another dictionary. print(student)
# 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 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Common Dictionary Methods
Operation Explanation Example
python student = {"name": "Alice", "age": 20}
Removes all elements from the
.clear() student.clear() print(student) # Output: {}
dictionary.

python student = {"name": "Alice", "age": 20} student_copy =


student.copy() student_copy["age"] = 21
Creates a shallow* copy of the
.copy() print(student) # Output: {'name': 'Alice', 'age': 20}
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 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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.

https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/dictionary-telephone-directory.py

Page 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Thank You

Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai (Autonomous)
[email protected]

Page 17 Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective content creators.
Document is compiled exclusively for study purpose and shall not be used for commercial purpose.

You might also like