SlideShare a Scribd company logo
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C HA PT E R 9
Dictionaries
and Sets
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Dictionaries
Sets
Serializing Objects
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Dictionaries
Dictionary: object that stores a
collection of data
Each element consists of a key and a value
Often referred to as mapping of key to value
Key must be an immutable object
To retrieve a specific value, use the key
associated with it
Format for creating a dictionary
dictionary =
{key1:val1, key2:val2}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Retrieving a Value from a
Dictionary
Elements in dictionary are unsorted
General format for retrieving value from
dictionary: dictionary[key]
If key in the dictionary, associated value is
returned, otherwise, KeyError exception is
raised
Test whether a key is in a dictionary
using the in and not in operators
Helps prevent KeyError exceptions
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Adding Elements to an
Existing Dictionary
Dictionaries are mutable objects
To add a new key-value pair:
dictionary[key] = value
If key exists in the dictionary, the value
associated with it will be changed
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Deleting Elements From an
Existing Dictionary
To delete a key-value pair:
del dictionary[key]
If key is not in the dictionary, KeyError
exception is raised
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting the Number of Elements
and Mixing Data Types
len function: used to obtain number of
elements in a dictionary
Keys must be immutable objects, but
associated values can be any type of
object
One dictionary can include keys of several
different immutable types
Values stored in a single dictionary can
be of different types
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating an Empty Dictionary and
Using for Loop to Iterate Over a
Dictionary
To create an empty dictionary:
Use {}
Use built-in function dict()
Elements can be added to the dictionary as
program executes
Use a for loop to iterate over a
dictionary
General format: for key in dictionary:
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Dictionary Methods
clear method: deletes all the elements
in a dictionary, leaving it empty
Format: dictionary.clear()
get method: gets a value associated
with specified key from the dictionary
Format: dictionary.get(key, default)
default is returned if key is not found
Alternative to [] operator
Cannot raise KeyError exception
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Dictionary Methods
(cont’d.)
items method: returns all the
dictionaries keys and associated
values
Format: dictionary.items()
Returned as a dictionary view
Each element in dictionary view is a tuple which
contains a key and its associated value
Use a for loop to iterate over the tuples in the
sequence
Can use a variable which receives a tuple, or can use
two variables which receive key and value
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Dictionary Methods
(cont’d.)
keys method: returns all the
dictionaries keys as a sequence
Format: dictionary.keys()
pop method: returns value associated
with specified key and removes that
key-value pair from the dictionary
Format: dictionary.pop(key, default)
default is returned if key is not found
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Dictionary Methods
(cont’d.)
popitem method: returns a randomly
selected key-value pair and removes
that key-value pair from the dictionary
Format: dictionary.popitem()
Key-value pair returned as a tuple
values method: returns all the
dictionaries values as a sequence
Format: dictionary.values()
Use a for loop to iterate over the values
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Dictionary Methods
(cont’d.)
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Sets
Set: object that stores a collection of
data in same way as mathematical set
All items must be unique
Set is unordered
Elements can be of different data types
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Creating a Set
set function: used to create a set
For empty set, call set()
For non-empty set, call set(argument)
where argument is an object that contains
iterable elements
e.g., argument can be a list, string, or tuple
If argument is a string, each character becomes a
set element
For set of strings, pass them to the function as a list
If argument contains duplicates, only one of the
duplicates will appear in the set
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Getting the Number of and
Adding Elements
len function: returns the number of
elements in the set
Sets are mutable objects
add method: adds an element to a set
update method: adds a group of
elements to a set
Argument must be a sequence containing
iterable elements, and each of the elements is
added to the set
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Deleting Elements From a Set
remove and discard methods: remove
the specified item from the set
The item that should be removed is passed to
both methods as an argument
Behave differently when the specified item is
not found in the set
remove method raises a KeyError exception
discard method does not raise an exception
clear method: clears all the elements
of the set
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using the for Loop, in, and
not in Operators With a Set
A for loop can be used to iterate over
elements in a set
General format: for item in set:
The loop iterates once for each element in the
set
The in operator can be used to test
whether a value exists in a set
Similarly, the not in operator can be used to
test whether a value does not exist in a set
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding the Union of Sets
Union of two sets: a set that contains
all the elements of both sets
To find the union of two sets:
Use the union method
Format: set1.union(set2)
Use the | operator
Format: set1 | set2
Both techniques return a new set which
contains the union of both sets
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding the Intersection of
Sets
Intersection of two sets: a set that
contains only the elements found in
both sets
To find the intersection of two sets:
Use the intersection method
Format: set1.intersection(set2)
Use the & operator
Format: set1 & set2
Both techniques return a new set which
contains the intersection of both sets
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding the Difference of Sets
Difference of two sets: a set that
contains the elements that appear in
the first set but do not appear in the
second set
To find the difference of two sets:
Use the difference method
Format: set1.difference(set2)
Use the - operator
Format: set1 - set2
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding the Symmetric
Difference of Sets
Symmetric difference of two sets: a set
that contains the elements that are not
shared by the two sets
To find the symmetric difference of two
sets:
Use the symmetric_difference method
Format: set1.symmetric_difference(set2)
Use the ^ operator
Format: set1 ^ set2
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding Subsets and
Supersets
Set A is subset of set B if all the
elements in set A are included in set B
To determine whether set A is subset
of set B
Use the issubset method
Format: setA.issubset(setB)
Use the <= operator
Format: setA <= setB
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Finding Subsets and
Supersets (cont’d.)
Set A is superset of set B if it contains
all the elements of set B
To determine whether set A is superset
of set B
Use the issuperset method
Format: setA.issuperset(setB)
Use the >= operator
Format: setA >= setB
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Serializing Objects
Serialize an object: convert the object
to a stream of bytes that can easily be
stored in a file
Pickling: serializing an object
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Serializing Objects (cont’d.)
To pickle an object:
Import the pickle module
Open a file for binary writing
Call the pickle.dump function
Format: pickle.dump(object, file)
Close the file
You can pickle multiple objects to one
file prior to closing the file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Serializing Objects (cont’d.)
Unpickling: retrieving pickled object
To unpickle an object:
Import the pickle module
Open a file for binary writing
Call the pickle.load function
Format: pickle.load(file)
Close the file
You can unpickle multiple objects from
the file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Summary
This chapter covered:
Dictionaries, including:
Creating dictionaries
Inserting, retrieving, adding, and deleting key-value
pairs
for loops and in and not in operators
Dictionary methods
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Summary (cont’d.)
This chapter covered (cont’d):
Sets:
Creating sets
Adding elements to and removing elements from
sets
Finding set union, intersection, difference and
symmetric difference
Finding subsets and supersets
Serializing objects
Pickling and unpickling objects

More Related Content

What's hot

How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
Edureka!
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
MSB Academy
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Python : Data Types
Python : Data TypesPython : Data Types
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Python list
Python listPython list
Python list
ArchanaBhumkar
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
ammarbrohi
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Python Collections
Python CollectionsPython Collections
Python Collections
sachingarg0
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | Edureka
Edureka!
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 

What's hot (20)

How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Python list
Python listPython list
Python list
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Generics
GenericsGenerics
Generics
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | Edureka
 
Python functions
Python functionsPython functions
Python functions
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 

Similar to Python Dictionaries and Sets

Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
Raajendra M
 
Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdf
alivaisi1
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
CruiseCH
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
Gina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
Gina Bullock
 
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
Gina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
Gina Bullock
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook Slides
DanWooster1
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
BienvenidoVelezUPR
 
Files and Exceptions
Files and ExceptionsFiles and Exceptions
Files and Exceptions
Munazza-Mah-Jabeen
 
Lecture 4 classes ii
Lecture 4 classes iiLecture 4 classes ii
Lecture 4 classes iithe_wumberlog
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Preparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesPreparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tables
Andres Mendez-Vazquez
 
Python for Everybody - Solution Challenge 2021
Python for Everybody - Solution Challenge 2021Python for Everybody - Solution Challenge 2021
Python for Everybody - Solution Challenge 2021
AshwinRaj57
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptx
SruthyPJ
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
DrRajeshreeKhande
 
set.pptx
set.pptxset.pptx
set.pptx
satyabratPanda2
 

Similar to Python Dictionaries and Sets (20)

Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Built-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdfBuilt-in Data Structures in python 3.pdf
Built-in Data Structures in python 3.pdf
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
CSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook SlidesCSCI 238 Chapter 08 Arrays Textbook Slides
CSCI 238 Chapter 08 Arrays Textbook Slides
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Files and Exceptions
Files and ExceptionsFiles and Exceptions
Files and Exceptions
 
Lecture 4 classes ii
Lecture 4 classes iiLecture 4 classes ii
Lecture 4 classes ii
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Preparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesPreparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tables
 
Python for Everybody - Solution Challenge 2021
Python for Everybody - Solution Challenge 2021Python for Everybody - Solution Challenge 2021
Python for Everybody - Solution Challenge 2021
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
 
COLLECTIONS.pptx
COLLECTIONS.pptxCOLLECTIONS.pptx
COLLECTIONS.pptx
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
set.pptx
set.pptxset.pptx
set.pptx
 

More from Nicole Ryan

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving Performance
Nicole Ryan
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search engines
Nicole Ryan
 
Inheritance
InheritanceInheritance
Inheritance
Nicole Ryan
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object model
Nicole Ryan
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and Audio
Nicole Ryan
 
Working with Images
Working with ImagesWorking with Images
Working with Images
Nicole Ryan
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and Animation
Nicole Ryan
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web Forms
Nicole Ryan
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and Tables
Nicole Ryan
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your website
Nicole Ryan
 
Working with Links
Working with LinksWorking with Links
Working with Links
Nicole Ryan
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSS
Nicole Ryan
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSS
Nicole Ryan
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSS
Nicole Ryan
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web Content
Nicole Ryan
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your Website
Nicole Ryan
 
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationChapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
Nicole Ryan
 
Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2
Nicole Ryan
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
Nicole Ryan
 
Programming Logic and Design: Arrays
Programming Logic and Design: ArraysProgramming Logic and Design: Arrays
Programming Logic and Design: Arrays
Nicole Ryan
 

More from Nicole Ryan (20)

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving Performance
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search engines
 
Inheritance
InheritanceInheritance
Inheritance
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object model
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and Audio
 
Working with Images
Working with ImagesWorking with Images
Working with Images
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and Animation
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web Forms
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and Tables
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your website
 
Working with Links
Working with LinksWorking with Links
Working with Links
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSS
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSS
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSS
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web Content
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your Website
 
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationChapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
 
Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
 
Programming Logic and Design: Arrays
Programming Logic and Design: ArraysProgramming Logic and Design: Arrays
Programming Logic and Design: Arrays
 

Recently uploaded

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

Python Dictionaries and Sets

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C HA PT E R 9 Dictionaries and Sets
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Dictionaries Sets Serializing Objects
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dictionaries Dictionary: object that stores a collection of data Each element consists of a key and a value Often referred to as mapping of key to value Key must be an immutable object To retrieve a specific value, use the key associated with it Format for creating a dictionary dictionary = {key1:val1, key2:val2}
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Retrieving a Value from a Dictionary Elements in dictionary are unsorted General format for retrieving value from dictionary: dictionary[key] If key in the dictionary, associated value is returned, otherwise, KeyError exception is raised Test whether a key is in a dictionary using the in and not in operators Helps prevent KeyError exceptions
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Adding Elements to an Existing Dictionary Dictionaries are mutable objects To add a new key-value pair: dictionary[key] = value If key exists in the dictionary, the value associated with it will be changed
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting Elements From an Existing Dictionary To delete a key-value pair: del dictionary[key] If key is not in the dictionary, KeyError exception is raised
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting the Number of Elements and Mixing Data Types len function: used to obtain number of elements in a dictionary Keys must be immutable objects, but associated values can be any type of object One dictionary can include keys of several different immutable types Values stored in a single dictionary can be of different types
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating an Empty Dictionary and Using for Loop to Iterate Over a Dictionary To create an empty dictionary: Use {} Use built-in function dict() Elements can be added to the dictionary as program executes Use a for loop to iterate over a dictionary General format: for key in dictionary:
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Dictionary Methods clear method: deletes all the elements in a dictionary, leaving it empty Format: dictionary.clear() get method: gets a value associated with specified key from the dictionary Format: dictionary.get(key, default) default is returned if key is not found Alternative to [] operator Cannot raise KeyError exception
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Dictionary Methods (cont’d.) items method: returns all the dictionaries keys and associated values Format: dictionary.items() Returned as a dictionary view Each element in dictionary view is a tuple which contains a key and its associated value Use a for loop to iterate over the tuples in the sequence Can use a variable which receives a tuple, or can use two variables which receive key and value
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Dictionary Methods (cont’d.) keys method: returns all the dictionaries keys as a sequence Format: dictionary.keys() pop method: returns value associated with specified key and removes that key-value pair from the dictionary Format: dictionary.pop(key, default) default is returned if key is not found
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Dictionary Methods (cont’d.) popitem method: returns a randomly selected key-value pair and removes that key-value pair from the dictionary Format: dictionary.popitem() Key-value pair returned as a tuple values method: returns all the dictionaries values as a sequence Format: dictionary.values() Use a for loop to iterate over the values
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Dictionary Methods (cont’d.)
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sets Set: object that stores a collection of data in same way as mathematical set All items must be unique Set is unordered Elements can be of different data types
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating a Set set function: used to create a set For empty set, call set() For non-empty set, call set(argument) where argument is an object that contains iterable elements e.g., argument can be a list, string, or tuple If argument is a string, each character becomes a set element For set of strings, pass them to the function as a list If argument contains duplicates, only one of the duplicates will appear in the set
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Getting the Number of and Adding Elements len function: returns the number of elements in the set Sets are mutable objects add method: adds an element to a set update method: adds a group of elements to a set Argument must be a sequence containing iterable elements, and each of the elements is added to the set
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting Elements From a Set remove and discard methods: remove the specified item from the set The item that should be removed is passed to both methods as an argument Behave differently when the specified item is not found in the set remove method raises a KeyError exception discard method does not raise an exception clear method: clears all the elements of the set
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using the for Loop, in, and not in Operators With a Set A for loop can be used to iterate over elements in a set General format: for item in set: The loop iterates once for each element in the set The in operator can be used to test whether a value exists in a set Similarly, the not in operator can be used to test whether a value does not exist in a set
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding the Union of Sets Union of two sets: a set that contains all the elements of both sets To find the union of two sets: Use the union method Format: set1.union(set2) Use the | operator Format: set1 | set2 Both techniques return a new set which contains the union of both sets
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding the Intersection of Sets Intersection of two sets: a set that contains only the elements found in both sets To find the intersection of two sets: Use the intersection method Format: set1.intersection(set2) Use the & operator Format: set1 & set2 Both techniques return a new set which contains the intersection of both sets
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding the Difference of Sets Difference of two sets: a set that contains the elements that appear in the first set but do not appear in the second set To find the difference of two sets: Use the difference method Format: set1.difference(set2) Use the - operator Format: set1 - set2
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding the Symmetric Difference of Sets Symmetric difference of two sets: a set that contains the elements that are not shared by the two sets To find the symmetric difference of two sets: Use the symmetric_difference method Format: set1.symmetric_difference(set2) Use the ^ operator Format: set1 ^ set2
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding Subsets and Supersets Set A is subset of set B if all the elements in set A are included in set B To determine whether set A is subset of set B Use the issubset method Format: setA.issubset(setB) Use the <= operator Format: setA <= setB
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding Subsets and Supersets (cont’d.) Set A is superset of set B if it contains all the elements of set B To determine whether set A is superset of set B Use the issuperset method Format: setA.issuperset(setB) Use the >= operator Format: setA >= setB
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Serializing Objects Serialize an object: convert the object to a stream of bytes that can easily be stored in a file Pickling: serializing an object
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Serializing Objects (cont’d.) To pickle an object: Import the pickle module Open a file for binary writing Call the pickle.dump function Format: pickle.dump(object, file) Close the file You can pickle multiple objects to one file prior to closing the file
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Serializing Objects (cont’d.) Unpickling: retrieving pickled object To unpickle an object: Import the pickle module Open a file for binary writing Call the pickle.load function Format: pickle.load(file) Close the file You can unpickle multiple objects from the file
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary This chapter covered: Dictionaries, including: Creating dictionaries Inserting, retrieving, adding, and deleting key-value pairs for loops and in and not in operators Dictionary methods
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary (cont’d.) This chapter covered (cont’d): Sets: Creating sets Adding elements to and removing elements from sets Finding set union, intersection, difference and symmetric difference Finding subsets and supersets Serializing objects Pickling and unpickling objects