Module 3
Module 3
Module – 3
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing, Using Data
Structures to Model Real-World Things.
Manipulating Strings: Working with Strings, Putting Strings Inside Other Strings, Useful
String Methods, Numeric Values of Characters with the ord() and chr() Functions, Coping and
Pasting Strings with the pyperclip Module,
Project: Multi-Clipboard Automatic Messages.
Example:
student_details = {
"name":"BMSIT",
"Roll_No":"1BY24CS100",
"PIN":560119
}
Dept. of CSE 1
Dictionaries & Strings
Here,
Name, Roll_NO, and PIN are keys,
BMSIT, 1BY24CS100, and 560119 are values.
Valid Keys Examples:
my_dict = {
101: "BMSIT", # int
"name": "BMS", # str
(1, 2): "Tuple Key" # tuple
}
Invalid Keys Examples
my_dict = {
[1, 2]: "List Key", # ❌ list is mutable
{1: "a"}: "Dict Key" # ❌ dict is mutable
}
# This will raise a TypeError
Real-Time Applications:
Storing Contact Information (Phone Book)
Student Marks Record
E-commerce Product Prices
Employee Details
Website Login Info (for simulation, not real storage)
Basic Dictionary Operations:
Operation Example Description
Add Item dict["newkey"] = value Add a new key-value pair
Change the value for an
Update Value dict["key"] = new_value
existing key
Delete Key del dict["key"] Remove key-value pair
Get Keys [Link]() Returns list of all keys
Get Values [Link]() Returns list of all values
Check Key Exists "key" in dict Returns True/False
Loop Through for key, value in
Iterate key-value pairs
Items [Link]():
Dept. of CSE 2
Dictionaries & Strings
Dept. of CSE 3
Dictionaries & Strings
>>> student_details['PERC']
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
student_details['PERC']
KeyError: 'PERC'
>>> print([Link]())
# Output: dict_values(['Tushar', 101, 'CSE', 88])
# Loop through values
>>> for value in [Link]():
print(value)
Dept. of CSE 5
Dictionaries & Strings
>>> print([Link]())
# Output: dict_items([('name', 'Tushar'), ('roll_no', 101),
('branch', 'CSE'), ('marks', 88)])
# Loop through key-value pairs
>>> for key, value in [Link]():
print(f"{key}: {value}")
NOTE:
keys_list = list([Link]()) # ['name', 'roll_no', 'branch', 'marks']
values_list = list([Link]())# ['Tushar', 101, 'CSE', 88]
items_list = list([Link]()) # [('name', 'Tushar'), ('roll_no', 101),
...]
Example:
student = {'name': 'Tushar', 'roll_no': 101, 'branch': 'CSE'}
# Check if 'name' key exists
>>> if 'name' in student:
print("Key 'name' exists.")
Dept. of CSE 6
Dictionaries & Strings
Pretty Printing:
pprint stands for pretty-print and is used to display complex data structures in a
readable and well-formatted way.
[Link](object) prints the pretty-formatted output directly to the console.
[Link](object) returns the pretty-formatted output as a string, useful for
logging or writing to files.
Feature [Link]() [Link]()
Purpose Prints formatted output to console Returns formatted output as a string
Return Value None (prints directly) Formatted string
Use Case Quick debugging or viewing data Storing or logging formatted data
Output Destination Standard output (console) Variable, file, or any string sink
Typical Usage [Link](obj) pretty_str= [Link](obj)
[Link](data) s = [Link](data) stores
Example
prints to screen formatted text
Customization
Accepts width, depth, sort_dicts Accepts same parameters
Parameters
Dept. of CSE 7
Dictionaries & Strings
Example:
import pprint
data = {
'name': 'Tushar',
'skills': ['Python', 'Machine Learning', 'Cybersecurity'],
'projects': [
{'title': 'Website Defacement Detection', 'year':2025},
{'title': 'Quantum AI Framework', 'year': 2024} ]
}
print("Using print():")
print(data)
print("=" * 20)
Dept. of CSE 8
Dictionaries & Strings
Case Study:
Using Data Structures to Model Real-World Things.
1. A Tic-Tac-Toe Board
Dept. of CSE 9
Dictionaries & Strings
MANIPULATING STRINGS
Introduction:
Text (Strings) is one of the most common data types handled in Python.
String Concatenation: Use the + operator to join strings.
“Python ” + “Programming” #Python Programming
String Slicing: Extract specific parts of a string.
>>> text = "Python"
>>> print(text[0:3]) # → 'Pyt'
Working with Strings:
String Literals:
A string literal is a fixed value of text written directly in your code.
It is enclosed in quotes: 'single' or "double".
Example:
‘Lists and dictionary are Mutable data types’
“Strings and Tuples are immutable data types”
Escape Character:
An escape character consists of a backslash (\) followed by the character you want
to add to the string.
Why Use Escape Characters?
To insert characters like:
Newlines (\n)
Tabs (\t)
Quotes inside strings (\' or \")
Backslashes (\\)
Example:
print('Single quote: \'')
print("Double quote: \"")
print("Backslash: \\")
print("Newline:\nThis is on a new line")
print("Tab:\tThis is after a tab space")
Dept. of CSE 10
Dictionaries & Strings
OUTPUT:
Raw Strings(r):
You can place an ‘r’ before the beginning quotation mark of a string to make it a raw
string.
A raw string completely ignores all escape characters and prints any back slash that
appears in the string.
Example:
>>> print("Strings are \nimmutable")
OUTPUT:
Strings are
immutable
>>> print(r"Strings are \nimmutable")
OUTPUT:
Strings are \nimmutable
Dept. of CSE 11
Dictionaries & Strings
Feature Explanation
No need for \n Newlines are included directly
Quotes inside
Single ' or double " quotes can be used inside
allowed
Python doesn't apply usual block indentation rules inside triple-
Ignores indentation
quoted text
Good for docstrings Used to write multi-line documentation for functions/classes
Indexing
Access a single character using its index:
Example:
>>> print(text[0]) # Output: H
>>> print(text[7]) # Output: w
>>> print(text[-1]) # Output: ! (last character using negative
indexing)
Slicing
Extract a substring using the syntax: string[start:end]
The start index is included, but the end index is excluded.
Dept. of CSE 12
Dictionaries & Strings
Example:
>>> print(text[0:5]) # Output: Hello
>>> print(text[7:12]) # Output: world
Omitting indexes:
print(text[:5]) # Output: Hello (from start to index 4)
print(text[7:]) # Output: world! (from index 7 to end)
Length of a String
Use len() to find the total number of characters (including spaces and symbols).
>>> len("Hello, world!") # Output: 13
Example:
>>> name = "BMSIT&M"
>>> print(f"Hello, {name}!")
Hello, BMSIT&M!
>>> print("Hello, %s" % name)
Hello, BMSIT&M
>>> print("Hello,{}".format(name))
Hello,BMSIT&M
>>> print("Hello," + name + "!")
Hello,BMSIT&M!
Dept. of CSE 14
Dictionaries & Strings
The isupper() and islower() methods will return a Boolean True value if the
string has atleast one letter and all the letters are uppercase
or lowercase, respectively. Otherwise, the method returns False.
Method Definition Example Output
"HELLO".isupper() True
Returns True if the string contains
"Hello".isupper() False
isupper() at least one letter and all letters
"123!".isupper()
are uppercase; else False. False
(no letters)
"hello".islower() True
Returns True if the string contains
"Hello".islower() False
islower() at least one letter and all letters
"123!".islower()
are lowercase; else False. False
(no letters)
Dept. of CSE 16
Dictionaries & Strings
The isX() string methods are helpful when you need to validate user input.
Example:
The following program repeatedly asks users for their age and a password until they provide
valid input.
while True:
print('Enter your age:')
age = input()
if [Link]():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if [Link]():
break
print('Passwords can only have letters and numbers.')
Dept. of CSE 17
Dictionaries & Strings
OUTPUT
Enter your age:
forty two
Please enter a number for your age.
Enter your age:
42
Select a new password (letters and numbers only):
secr3t!
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
secr3t
Dept. of CSE 18
Dictionaries & Strings
Dept. of CSE 19
Dictionaries & Strings
Dept. of CSE 20
Dictionaries & Strings
Dept. of CSE 21
Dictionaries & Strings
strip() Method
Removes leading and trailing whitespace (spaces, tabs, newlines) from a string.
Example:
>>> text = " Hello, World! \n"
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello, World!'
NOTE:
In Python, repr() stands for "representation" — specifically,
it returns a string that represents the object in a way that is
usually suitable for debugging and development.
lstrip() Method
Removes only leading (left-side) whitespace.
Example:
>>> text = " Hello"
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello'
rstrip() Method
Removes only trailing (right-side) whitespace.
Example:
>>> text = "Hello "
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello'
Dept. of CSE 22
Dictionaries & Strings
Dept. of CSE 23
Dictionaries & Strings
text = [Link]()
print("Clipboard contains:", text)
OUTPUT:
Clipboard contains: Hello from Python!
# You can now paste it anywhere (e.g., Notepad,
browser) using Ctrl + V.
Dept. of CSE 24