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

Unit 3 Python notes

Uploaded by

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

Unit 3 Python notes

Uploaded by

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

UNIT : 3 Dictionaries

Introduction to Python Dictionaries

A Python dictionary is a mutable, unordered collection that stores data in key-value pairs.
Each key must be unique, immutable, and hashable (e.g., strings, numbers, tuples), while the
values can be of any data type.

Syntax:

dictionary = {key1: value1, key2: value2, ...}

Example:

person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

Built-in Functions for Dictionaries

1. len(): Returns the number of items in the dictionary.

len(person) # Output: 3

2. dict(): Creates a dictionary.

new_dict = dict(name="Bob", age=30)

3. type(): Returns the type of the object.

type(person) # Output: <class 'dict'>

4. all(): Checks if all keys are truthy.

all({"a": 1, "b": 0}) # Output: False

5. any(): Checks if at least one key is truthy.

any({"a": 0, "b": 0, "c": 1}) # Output: True

6. sorted(): Returns a sorted list of dictionary keys.

sorted(person) # Output: ['age', 'city', 'name']

Built-in Methods for Dictionaries

1. get(): Retrieves the value of a key, with an optional default.


person.get("name") # Output: "Alice"
person.get("gender", "Not specified") # Output: "Not specified"

2. keys(): Returns a view object of all keys.

person.keys() # Output: dict_keys(['name', 'age', 'city'])

3. values(): Returns a view object of all values.

person.values() # Output: dict_values(['Alice', 25, 'New York'])

4. items(): Returns a view object of key-value pairs.

person.items() # Output: dict_items([('name', 'Alice'), ('age', 25),


('city', 'New York')])

5. update(): Updates the dictionary with key-value pairs from another dictionary or
iterable.

person.update({"gender": "Female"})

6. pop(): Removes a specified key and returns its value.

person.pop("age") # Output: 25

7. popitem(): Removes and returns the last inserted key-value pair.

person.popitem()

8. clear(): Empties the dictionary.

person.clear()

9. copy(): Returns a shallow copy of the dictionary.

new_person = person.copy()

10. setdefault(): Returns the value of a key; if it doesn’t exist, inserts it with a default
value.

person.setdefault("country", "USA")

Dictionary Keys

 Keys must be unique and immutable (e.g., strings, numbers, tuples).


 If a duplicate key is used during dictionary creation, the last value overrides the
previous ones.

Example:

my_dict = {"a": 1, "b": 2, "a": 3}


print(my_dict) # Output: {'a': 3, 'b': 2}

Sorting and Looping Through a Dictionary

Sorting

 Sort keys:

sorted(person) # Output: ['age', 'city', 'name']

 Sort by values:

sorted(person.items(), key=lambda x: x[1])

Looping

1. Iterate over keys:

for key in person:


print(key)

2. Iterate over values:

for value in person.values():


print(value)

3. Iterate over key-value pairs:

for key, value in person.items():


print(f"{key}: {value}")

Nested Dictionaries

A dictionary can contain other dictionaries as values.

Example:

students = {
"student1": {"name": "John", "age": 20},
"student2": {"name": "Jane", "age": 22}
}

 Accessing nested values:

students["student1"]["name"] # Output: "John"


Nested Functions in Dictionaries

A nested function is defined inside another function and can be used for encapsulation or
utility in a dictionary context.

Example:

def outer_function():
def inner_function():
return "Hello, World!"
return inner_function

my_dict = {"greet": outer_function()}


print(my_dict["greet"]()) # Output: "Hello, World!"

File Structure

1. File Objects in Python


In Python, file objects are used to interact with files stored on a computer. They allow reading
from and writing to files, providing a structured way to manage input/output operations.
Python provides the built-in open() function to create file objects, offering a wide range of
functionalities for file manipulation. Here's a detailed look at file objects in Python:

1. Opening a File
The open() function is used to open a file and return a file object. Its syntax is:

open(file, mode='r', buffering=-1, encoding=None, errors=None,


newline=None, closefd=True, opener=None)

Parameters:

 file: Path to the file (relative or absolute).


 mode: Determines the mode of access:
o 'r': Read (default).
o 'w': Write (overwrites the file if it exists).
o 'x': Create (fails if the file exists).
o 'a': Append (writes to the end of the file if it exists).
o 'b': Binary mode.
o 't': Text mode (default).
o '+': Read and write.
 buffering: Controls buffering. Use 0 for no buffering, 1 for line buffering, or an
integer for a specific buffer size.
 encoding: Specifies the encoding (e.g., 'utf-8' for text files).
 errors: How to handle encoding/decoding errors.
 newline: Controls how newline characters are handled.
 closefd: Boolean to determine if the underlying file descriptor is closed when the file
is closed.
 opener: A custom opener for file descriptors.

Example:
file = open("example.txt", "r")

2. File Modes
Mode Description
'r' Read-only. File must exist.
'w' Write-only. Creates a new file or truncates an existing one.
'x' Exclusive creation. Fails if the file exists.
'a' Append. Writes data at the end of the file.
'b' Binary mode.
't' Text mode (default).
'+' Read and write.

3. Reading Files
File objects provide methods to read data:

 read(size): Reads size bytes (or the whole file if size is not specified).
 readline(): Reads a single line.
 readlines(): Reads all lines into a list.

Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

4. Writing to Files
File objects also allow writing data:

 write(string): Writes a string to the file.


 writelines(lines): Writes a list of strings to the file.

Example:
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

5. Closing a File
Always close a file after use to free system resources. Use the close() method:

file.close()

Alternatively, use a context manager (with statement), which automatically closes the file:

with open("example.txt", "r") as file:


content = file.read()

6. File Attributes
File objects have attributes that provide additional information:

 file.name: Name of the file.


 file.mode: Mode in which the file was opened.
 file.closed: Boolean indicating if the file is closed.
 file.encoding: Encoding used (text files only).

7. Binary Files
For binary files, use the 'b' mode. Operations read/write raw binary data.

Example:
with open("example.bin", "wb") as file:
file.write(b'\x00\xFF\x10')

8. Other Useful Methods


 seek(offset, whence): Moves the file pointer to a specified location.
 tell(): Returns the current position of the file pointer.
 flush(): Flushes the write buffer to disk.
 truncate(size): Resizes the file.
2. File Built-in Functions
Python provides built-in functions for file handling, including creation, reading, writing, and
manipulation.

Common File Built-in Functions:

Function Description
open() Opens a file and returns a file object.
close() Closes the file.
read() Reads the content of a file.
write() Writes to a file.
readline() Reads a single line from the file.
readlines() Reads all lines from the file into a list.
writelines() Writes a list of lines to a file.
seek() Moves the file pointer to a specific position.
tell() Returns the current position of the file pointer.
flush() Flushes the internal buffer, ensuring data is written to the file.
truncate()
Resizes the file to a specified size.

with statement . Context manager to ensure the file is properly closed after operations

1. open()

 Used to open a file and create a file object.


 Syntax:

file = open(filename, mode, buffering, encoding)

 Example:

file = open("example.txt", "r")

2. close()

 Closes the file to release resources.


 Example:

file.close()

3. read()

 Reads the entire file or up to the specified number of bytes.


 Example:

content = file.read(100) # Read first 100 bytes


4. readline()

 Reads a single line from the file.


 Example:

line = file.readline()

5. readlines()

 Reads all lines from the file and returns them as a list of strings.
 Example:

lines = file.readlines()

6. write()

 Writes a string to the file.


 Example:

file = open("example.txt", "w")


file.write("Hello, World!")
file.close()

7. writelines()

 Writes a list of strings to the file.


 Example:

lines = ["Line 1\n", "Line 2\n"]


file.writelines(lines)

8. seek()

 Moves the file pointer to a specified position.


 Syntax:

file.seek(offset, whence)

 Example:

file.seek(0) # Move to the beginning of the file

9. tell()

 Returns the current position of the file pointer.


 Example:

position = file.tell()

10. flush()
 Flushes the internal buffer to write data to the disk immediately.
 Example:

file.flush()

11. truncate()

 Resizes the file to the specified size.


 Example:

file.truncate(50) # Truncate file to 50 bytes

12. Using with Statement

 Ensures the file is properly closed after operations.


 Example:

with open("example.txt", "r") as file:


content = file.read()

Utility Functions for Files

1. os and shutil Modules

 Provide additional functions for file handling.


 Examples:

import os
os.rename("old.txt", "new.txt")
os.remove("file.txt")

2. pathlib Module

 Modern file manipulation with a more intuitive API.


 Example:

from pathlib import Path


file = Path("example.txt")
print(file.read_text())

3. File Built-in Methods


These methods are available on file objects:

Method Description
file.read(size) Reads at most size characters (or bytes).
file.write(data) Writes data to the file.
file.readlines() Reads all lines into a list.
Method Description
file.seek(offset) Moves the pointer to the given offset.
file.tell() Returns the current file pointer position.

4. File Built-in Attributes


File objects have several attributes that provide information about the file.

Attribute Description
file.name The name of the file.
file.mode The mode in which the file was opened (r, w, a, etc.).
file.closed Returns True if the file is closed.
file.encoding The encoding of the file (if applicable).

5. Standard Files
Standard files are the three predefined streams available in Python:

 Standard Input (stdin): Used to read input from the user (e.g., input()).
 Standard Output (stdout): Used to display output (e.g., print()).
 Standard Error (stderr): Used to display error messages.

Example:
import sys

# Writing to stdout
sys.stdout.write("Hello, stdout!\n")

# Writing to stderr
sys.stderr.write("An error occurred!\n")

6. Command-Line Arguments
Command-line arguments can be accessed using the sys.argv list. The first element is the
script name, and subsequent elements are the passed arguments.

Example:
import sys

# Accessing command-line arguments


print("Script name:", sys.argv[0])
if len(sys.argv) > 1:
print("Arguments:", sys.argv[1:])
Run Command:

bash
script.py arg1 arg2

Output:

less
Script name: script.py
Arguments: ['arg1', 'arg2']

7. File System
Python provides the os and shutil modules for interacting with the file system.

Common Operations:

Operation Code
Check if a file exists os.path.exists("file.txt")
Get the current directory os.getcwd()
Create a directory os.mkdir("new_dir")
Remove a file os.remove("file.txt")
Rename a file os.rename("old.txt", "new.txt")
Copy a file shutil.copy("src.txt", "dest.txt")

8. File Execution Notes


When handling files in Python, consider the following best practices:

 Always close the file after using it to avoid resource leaks.


 Use context managers (with statement) to manage file operations safely:

with open("example.txt", "r") as file:


data = file.read()
# File is automatically closed after the block

 Use appropriate file modes (r, w, a, b, etc.) based on the operation.

Common File Modes:

Mode Description
r Read-only mode.
w Write-only mode. Overwrites existing files.
a Append mode. Adds content to the end of the file.
Mode Description
b Binary mode (e.g., rb, wb).
x Exclusive creation mode. Fails if the file exists.

You might also like