Gaddis Python 6e Chapter 09
Chapter Overview
Title: R Python Sixth Edition Chapter 9
Author: Tony Gaddis
Focus: This chapter focuses on Dictionaries and Sets in Python.
Topics Covered
Dictionaries
Sets
Serializing Objects
Dictionaries
Definition
A dictionary is an object that stores a collection of data in key-value pairs.
Keys must be immutable objects (e.g., strings, numbers, tuples).
Example Format:
dictionary = {key1:val1, key2:val2}.
Retrieving Values
Dictionary elements are unsorted.
Use the format
dictionary[key]to retrieve values.If the key does not exist, a
KeyErrorexception is raised.Use
inoperator to check for key existence.
Adding Elements
Dictionaries are mutable.
To add a new key-value pair, use
dictionary[key] = value.If the key exists, its value is updated.
Deleting Elements
Use
del dictionary[key]to remove a key-value pair.If the key does not exist, a
KeyErroris raised.
Other Dictionary Features
Counting Elements
Use
len(dictionary)to count the number of elements in a dictionary.
Mixing Data Types
Keys must be immutable, but values can be of any data type.
Supports multiple immutable keys.
Creating Dictionaries
For an empty dictionary:
dict1 = {}ordict().Elements can be added during program execution.
Dictionary Methods
Common Methods
clear(): Deletes all elements.
get(key, default): Retrieves value without raising
KeyError.items(): Returns all key-value pairs as tuples.
keys(): Returns all keys.
pop(key, default): Removes specified key and returns its value.
popitem(): Returns and removes the last added key-value pair.
values(): Returns all values as a sequence.
Merging and Updating Dictionaries
Merge Operator (
|): Combines two dictionaries, keeping the right-hand value for duplicate keys.Example:
dict3 = dict1 | dict2.
Update Operator (
|=): Merges another dictionary into the existing one.Example:
dict1 |= dict2.
Dictionary Comprehensions
A concise way to create dictionaries from iterable elements.
Example:
squares = {item: item**2 for item in [1, 2, 3, 4]}Allows use of if-conditions to filter elements.
Sets
Definition
A set is an unordered collection of unique items.
Elements can be of various data types; duplicates are not stored.
Creating Sets
Use
set()for an empty set orset(iterable)for a filled one.Example: Strings treated character-wise if passed as strings.
Operations on Sets
Basic Functions
len(set): Counts elements in the set.
add(value): Adds an element to the set.
update(iterable): Adds multiple elements.
Deleting Elements
remove(value): Removes a specified item. Raises
KeyErrorif not found.discard(value): Removes the item without raising an error.
clear(): Removes all elements.
Loops and Membership Testing
Use
for item in set:to iterate.Use
inandnot inoperators to check membership.
Set Operations
Union, Intersection, and Difference
Union: Combines two sets.
Method:
set1.union(set2)orset1 | set2.
Intersection: Common elements between two sets.
Method:
set1.intersection(set2)orset1 & set2.
Difference: Elements in one set but not the other.
Method:
set1.difference(set2)orset1 - set2.
Symmetric Difference: Unshared elements.
Method:
set1.symmetric_difference(set2)orset1 ^ set2.
Subset and Superset Methods
issubset(): Checks if all elements of A are in B.
issuperset(): Checks if all elements of B are in A.
Syntax:
setA.issubset(setB)orsetA >= setB.
Set Comprehensions
Similar to list comprehensions, but use curly braces.
Example:
set2 = {item for item in set1 if item < 10}
Serializing Objects
Definition
Serialization: Converting an object into bytes for storage.
Pickling: The process of serializing an object in Python.
Pickling an Object
Steps:
Import pickle module.
Open a file in binary write mode.
Use
pickle.dump(object, file).
Unpickling an Object
Steps:
Import pickle module.
Open a file in binary read mode.
Use
pickle.load(file)to retrieve the object.
Summary
This chapter covered:
Dictionaries:
Creation, insertion, retrieval, deletion, and associated methods.
Sets:
Creation, addition, removal, operations, and comprehension.
Serializing Objects:
Pickling and unpickling objects.