0% found this document useful (0 votes)
8 views45 pages

Dictionaries Sets Unit3

Uploaded by

tharunkumar0973
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Dictionaries Sets Unit3

Uploaded by

tharunkumar0973
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

CHAPTER 9

Dictionarie
s and Sets

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Topics

Dictionaries
Sets
Serializing Objects

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Dictionaries
Dictionary:
In Python, a dictionary is an object that stores a collection of data.
Each element consists of a key and a value and is referred to as
key-value pairs ,use a key to locate a specific value
Key-value pairs are often referred to as mappings because each key
is mapped to a value.
You can create a dictionary by enclosing the elements inside a set
of curly braces ( {} ).
• Format for creating a dictionary
dictionary = {key1:val1, key2:val2}
The values in a dictionary can be objects of any type, but the keys
must be immutable objects.
For example, keys can be strings, integers, floating-point values, or
tuples. Keys cannot be lists.
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
Keys

To retrieve a specific value, use the key associated with it


The values in a dictionary can be objects of any type, but the
keys must be immutable objects.
For example, keys can be strings, integers, floating-point
values, or tuples.
Keys cannot be lists or any other type of immutable object.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Retrieving a Value from a Dictionary
Elements in dictionary are not stored in any particular order i.e.,
they are unsorted.
Dictionaries are not sequences, like lists, tuples, and strings. As a
result, you cannot use a numeric index to retrieve a value by its
position from a dictionary. Instead, you use a key to retrieve a
value.
General format for retrieving value from dictionary:
dictionary[key]
If key in the dictionary, associated value is returned, otherwise,
KeyError exception is raised
phonebook = {'Chris':'555-1111', 'Katie':'555-2222‘,
'Joanne':'555-3333'}
phonebook['Chris'] O/p:'555-1111'
Remember that string comparisons are case sensitive.
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
Using the in and not in Operators to Test
for a Value in a Dictionary
Helps prevent KeyError exceptions, we can use the in operator
to determine whether a key exists before you try to use it to
retrieve a value.
phonebook = {'Chris':'555−1111', 'Katie':'555−2222',
'Joanne':'555−3333'}
>>> if 'Chris' in phonebook:
print(phonebook['Chris'])
>>> if ‘joanne' not in phonebook:
print('Joanne is not found.')
Keep in mind that string comparisons with the in and not
in operators are case sensitive.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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.
If the key does not exist, it will be added to the dictionary,
along with value as its associated value.
>>> phonebook = {'Chris':'555−1111', 'Katie':'555−2222',
'Joanne':'555−3333'}
>>> phonebook['Joe'] = '555−0123'
>>> phonebook['Chris'] = '555−4444'
>>> phonebook
{'Chris': '555-4444', 'Joanne': '555−3333', 'Joe':
'555−0123‘,'Katie': '555−2222'}
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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
del phonebook['Chris']
To prevent a KeyError exception from being raised, you
should use the in operator to determine whether a key exists
before you try to delete it and its associated value.
if 'Chris' in phonebook:
del phonebook['Chris']

Note: You cannot have duplicate keys in a dictionary. When you assign a
value to an existing key, the new value replaces the existing value.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Getting the Number of Elements

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
phonebook = {'Chris':'555−1111', 'Katie':'555−2222'}
num_items = len(phonebook)
print(num_items)

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Mixing Data Types in a Dictionary
test_scores = { 'Kayla' : [88, 92, 100], 'Luis' : [95, 74, 81],
'Sophie' : [72, 88, 91], 'Ethan' : [70, 75, 78] }
>>> test_scores
kayla_scores = test_scores['Kayla']
>>> print(kayla_scores)
The values that are stored in a single dictionary can be of different
types. For example, one element’s value might be a string, another
element’s value might be a list, and yet another element’s value
might be an integer. The keys can be of different types, too, as
long as they are immutable.
mixed_up = {'abc':1, 999:'yada yada', (3, 6, 9):[3, 6, 9]}
>>> mixed_up O/P: {(3, 6, 9): [3, 6, 9], 'abc': 1, 999: 'yada yada'}
employee = {'name' : 'Kevin Smith', 'id' : 12345, 'payrate' :
25.75 }
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
Creating an Empty Dictionary and Using for
Loop to Iterate Over a Dictionary
To create an empty dictionary:
Use {} phonebook = {}
phonebook['Chris'] = '555-1111'
Use built-in function dict()
phonebook = dict()
After execution, the phonebook variable will reference an empty
dictionary
Elements can be added to the dictionary as program executes

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Use a for loop to iterate over a dictionary for key in dictionary:
for var in dictionary:
statement
statement
etc.
phonebook = {'Chris':'555−1111', 'Katie':'555−2222',
'Joanne':'555−3333'}
for key in phonebook:
print(key)
O/P:Chris
Joanne
Katie
for key in phonebook:
print(key, phonebook[key])

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Some Dictionary Methods (cont’d.)

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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

Pg no 395
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


For loop to iterate over the tuples in the sequence.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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
You can use an assignment statement in the following general
format to assign the returned key and value to individual
variables: k, v = dictionary.popitem()
This type of assignment is known as a multiple assignment
because multiple variables are being assigned at once.
In format, k and v are variables. After the statement executes, k
is assigned a randomly selected key from the dictionary, and v
is assigned the value associated with that key.
The key-value pair is removed from the dictionary.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


values method: returns all the dictionaries values
(without their keys) as a dictionary view, which is a type of
sequence.
Format: dictionary.values()
Use a for loop to iterate over the values

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Sets
Set: It is an object that stores a collection of data in same
way as mathematical set
All items must be unique, No two elements can have the
same value.
Set is unordered
Elements can be of different data types
Sets cannot contain duplicate elements.
If you pass an argument containing duplicate elements
to the set function, only one of the duplicated elements will
appear in the set.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Creating a Set

set function: used to create a set


For empty set, call myset = set()
For non-empty set, call set(argument) where argument
is an object that contains iterable elements
myset = set(['a', 'b', 'c'])
e.g., argument can be a list, string, or tuple
If argument is a string, each character becomes a set
element myset = set('abc')
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 myset = set('aaabc')
O/P: ‘a', 'b', and 'c'.
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
how would you create a set containing the elements 'one',
'two', and 'three'?
myset = set('one', 'two', 'three') # This is an ERROR!
myset = set(['one‘ , 'two', 'three'])
O/P: 'one', 'two', and 'three'.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Getting the Number of and Adding Elements
len function: returns the number of elements in the set
myset = set([1, 2, 3, 4, 5])
len(myset) O/P: 5
Sets are mutable objects
add method: adds an element to a set
myset = set()
myset.add(1)
myset.add(2)
myset.add(3)
myset O/P: {1, 2, 3}
myset.add(2) #the method does not raise an
exception.
myset O/P: {1, 2, 3}
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
update method: adds a group of elements to a set all at
one time
Argument must be a sequence containing iterable
elements, such as a list, a tuple, string, or another set. and
each of the elements is added to the set
The individual elements of the object that you pass as an
argument become elements of the set.
myset = set([1, 2, 3]) myset = set([1, 2, 3])
myset.update('abc')
myset.update([4, 5, 6])
myset
myset O/P:{1, 2, 3, 4, 5, 6} O/P:
set1 = set([1, 2, 3]) {'a', 1, 2, 3, 'c', 'b'}

set2 = set([8, 9, 10])


set1.update(set2)
set1 O/P: {1, 2, 3, 8, 9, 10}
Set2 O/P: {8, 9, 10}
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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
Both 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
myset = set([1, 2, 3,4,5])
myset.remove(1) myset.discard(5)
myset O/P: {2, 3, 4}
myset.discard(99)
myset.remove(99) # KeyError: 99
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
clear method: clears all the elements of the set
myset = set([1, 2, 3, 4, 5])
myset O/P:{1, 2, 3, 4, 5}
myset.clear()
myset
set()

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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:
for var in set:
statement
statement
etc.
The loop iterates once for each element in the set
myset = set(['a', 'b', 'c'])
for val in myset: O/P: a
print(val) b
c

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
myset = set([1, 2, 3])
if 1 in myset:
print('The value 1 is in the set.')
O/P: The value 1 is in the set.
myset = set([1, 2, 3])
if 99 not in myset:
print('The value 99 is not in the set.')

O/P: The value 99 is not in the set.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
set1 = set([1, 2, 3, 4]) set2 = set([3, 4, 5, 6])
set3 = set1 | set2 set3
O/P :{1, 2, 3, 4,
M.Trupthi, Assistant Professor,5, 6}of IT, CBIT, Hyderabad.
Dept.
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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.difference(set2)
set3 O/P:{1, 2}

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.symmetric_difference(set2)
set3 O/P; {1, 2, 5, 6}

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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
The method returns True if set2 is a subset of set1. Otherwise, it
returns False.
set1 = set([1, 2, 3, 4])
set2 = set([2, 3])
set2.issubset(set1) True
set1.issuperset(set2) True
7
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Serializing Objects

Serialize an object: convert the object to a stream of bytes


that can easily be stored in a file
Pickling: It means serializing an object

Pickling - is the process whereby a Python object hierarchy is


converted into a byte stream, and Unpickling - is the inverse
operation, whereby a byte stream is converted back into
an object hierarchy. Pickling (and unpickling) is
alternatively known as serialization, marshalling, or flattening.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Serializing Objects

Sometimes you need to store the contents of a complex object,


such as a dictionary or a set, to a file.
The easiest way to save an object to a file is to serialize the
object.
When an object is serialized, it is converted to a stream of
bytes that can be easily stored in a file for later retrieval.
In Python, the process of serializing an object is referred to as
pickling.
The Python standard library provides a module named pickle
that has various functions for serializing, or pickling, objects.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


Once you import the pickle module, you perform the following steps to
pickle an object:
You open a file for binary writing.
You call the pickle module’s dump method to pickle the object and write it
to the specified file.
After you have pickled all the objects that you want to save to the file, you
close the file.
To open a file for binary writing, you use 'wb‘ as the mode when you call
the open function.

To pickle an object:
Import the pickle module
Open a file for binary writing
Call the pickle.dump function and write it to the specified file.
Format: pickle.dump(object, file)
Close the file
You can pickle multiple objects to one file prior to closin the file

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


How to do it
The following statement opens a file named
mydata.dat for binary writing:
outputfile = open('mydata.dat', 'wb')
Once you have opened a file for binary writing, you
call the pickle module’s dump function.
Here is the general format of the dump method:
pickle.dump(object, file)
In the general format, object is a variable that
references the object you want to pickle, and file is
a variable that references a file object.
After the function executes, the object referenced
by object will be serialized and written to the file.
You can pickle just about any type of object,
including lists, tuples, dictionaries, sets, strings,
integers, and floating point numbers.
M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
Serializing Objects (cont’d.)

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


unpickle

To retrieve, or unpickle, the objects that you have pickled.


You open a file for binary reading.
You call the pickle module’s load function to retrieve an
object from the file and unpickle it.
After you have unpickled all the objects that you want from
the file, you close the file.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


unpickle
To open a file for binary reading, you use 'rb' as the mode when you call the open
function.
For example, the following statement opens a file named mydata.dat for binary
reading:
inputfile = open('mydata.dat', 'rb')
Once you have opened a file for binary reading, you call the pickle module’s load
function.
Here is the general format of a statement that calls the load function:
object = pickle.load(file)
In the general format, object is a variable, and file is a variable that references a
file object.
After the function executes, the object variable will reference an object that was
retrieved from the file and unpickled.
You can unpickle as many objects as necessary from the file.
(If you try to read past the end of the file, the load function will raise an EOFError
exception.)
When you are finished, you call the file object’s close method to close the file.

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.
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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.


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

M.Trupthi, Assistant Professor, Dept. of IT, CBIT, Hyderabad.

You might also like