Lec 017
Lec 017
Business
Instructor: Wania Fatima
[email protected]
Dictionaries & Sets
Dictionaries
• A dictionary is an object that stores a collection of data.
• Each element in a dictionary has two parts:
1. a key
2. a value
• You use a key to locate a specific value.
Dictionaries
•A dictionary in Python is an object that stores a collection of data.
•Each element in a dictionary is a key-value pair:
•Key: Identifier or lookup value
•Value: Data associated with the key
•To retrieve a value, use its associated key.
•Example:
•Like a real dictionary:
•Word → Key
•Definition → Value
•Use case: Employee Lookup
•Each employee has an ID number.
•Create a dictionary:
•Key = Employee ID
•Value = Employee Name
•Entering an employee ID retrieves the employee’s name.
Creating Dictionaries
• You can create a dictionary by enclosing the elements inside a set of curly braces ( {} ).
•An element consists of a key, followed by a colon, followed by a value. The elements are
•separated by commas. The following statement shows an example:
• phonebook = {'Chris’ : '555−1111', 'Katie’ : '555−2222', 'Joanne’ : '555−3333’}
Creating Dictionaries
This statement creates a dictionary and assigns it to the phonebook variable. The dictionary
contains the following three elements:
•The first element is 'Chris':'555−1111'. In this element, the key is 'Chris' and
the value is '555−1111'.
•The second element is 'Katie':'555−2222'. In this element, the key is 'Katie' and
the value is '555−2222'.
•The third element is 'Joanne':'555−3333'. In this element, the key is 'Joanne' and the value is
'555−3333'.
Retrieving Values from Dictionaries
The elements in a dictionary are not stored in any particular order. For example, look at the
following interactive session in which a dictionary is created and its elements are displayed:
>>> phonebook = {'Chris':'555−1111', 'Katie':'555−2222', 'Joanne':'555−3333'}
>>> phonebook
{'Chris': '555−1111', 'Joanne': '555−3333', 'Katie': '555−2222'}
>>>
Notice the order in which the elements are displayed is different than the order in which
they were created. This illustrates how 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.
Retrieving Values from Dictionaries
To retrieve a value from a dictionary, you simply write an expression in the following general
format:
dictionary_name[key]
Using the in and not in Operators to Test for a Value
in a Dictionary
• A KeyError exception is raised if you try to retrieve a value from a dictionary using a
nonexistent key.
• To prevent such an exception, you can use the in operator to determine whether a key
exists before you try to use it to retrieve a value.
Using the in and not in Operators to Test for a Value
in a Dictionary
• You can also use the not in operator to determine whether a key does not exist, as dem
onstrated in the following session:
Adding Elements to an Existing Dictionary
• Dictionaries are mutable objects. You can add new key-value pairs to a dictionary with an
assignment statement in the following general format:
dictionary_name[key] = value
Getting the Number of Elements in a Dictionary
• You can use the built-in len function to get the number of elements in a dictionary.
Mixing Data Types in a Dictionary
• As previously mentioned, the keys in a dictionary must be immutable objects, but their
associated values can be any type of object.
Mixing Data Types in a Dictionary
• As previously mentioned, the keys in a dictionary must be immutable objects, but their
associated values can be any type of object.
Creating an Empty Dictionary
• Sometimes, you need to create an empty dictionary and then add elements to it as the
pro gram executes.
Using the for Loop to Iterate over a Dictionary
• You can use the for loop in the following general format to iterate over all the keys in a
• dictionary:
for var in dictionary:
statement
statement
etc.
In the general format, var is the name of a variable and dictionary is the name of a dictionary.
This loop iterates once for each element in the dictionary.
Using the for Loop to Iterate over a Dictionary
Some Dictionary Methods
The get Method
• You can use the get method as an alternative to the [ ] operator for getting a value from a
dictionary. value = my_dict[key]
• Here is the method’s general format:
dictionary.get(key, default)
• dictionary is the name of a dictionary, key is a key to search for in the dictionary, and
default is a default value to return if the key is not found.
• When the method is called, it returns the value that is associated with the specified key. If
the specified key is not found in the dictionary, the method returns default.
The get Method
The items Method
• The items method returns all of a dictionary’s keys and their associated values. They are
returned as a special type of sequence known as a dictionary view. Each element in the
dictionary view is a tuple, and each tuple contains a key and its associated value.
phonebook = {'Chris':'555−1111', 'Katie':'555−2222', 'Joanne':'555−3333'}
• If we call the phonebook.items() method, it returns the following sequence:
[('Chris', '555−1111'), ('Joanne', '555−3333'), ('Katie', '555−2222’)]
The items Method
The keys Method
• The keys method returns all of a dictionary’s keys as a dictionary view, which is a type of
sequence. Each element in the dictionary view is a key from the dictionary.
• You can delete an existing key-value pair from a dictionary with the del statement. Here is
the general format:
del dictionary_name[key]
The pop Method
• The pop method returns the value associated with a specified key and removes that key
value pair from the dictionary. If the key is not found, the method returns a default value.
Here is the method’s general format:
dictionary.pop(key, default)
In the general format, dictionary is the name of a dictionary, key is a key to search for in the
dictionary, and default is a default value to return if the key is not found. When the method is
called, it returns the value that is associated with the specified key, and it removes that key-
value pair from the dictionary. If the specified key is not found in the dictionary, the method
returns default.
The pop Method
The popitem Method
• Removes and returns the last inserted key-value pair.
• Returns a tuple: (key, value).
• Does not need a key.
dictionary.popitem()
• 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()
The popitem Method
Example
Sets
Sets
• A set contains a collection of unique values and works like a mathematical set.
• A set is an object that stores a collection of data in the same way as mathematical sets.
Here are some important things to know about sets:
All the elements in a set must be unique. No two elements can have the same value.
Sets are unordered, which means that the elements in a set are not stored in any par
ticular order.
The elements that are stored in a set can be of different data types.
Creating Sets
• To create a set, you have to call the built-in set function. Here is an example of how you
create an empty set:
myset = set()
• After this statement executes, the myset variable will reference an empty set.
myset = set(['a', 'b', 'c’])
• In this example, we are passing a list as an argument to the set function. After this
statement executes, the myset variable references a set containing the elements 'a', 'b',
and ‘c’.
• If you pass a string as an argument to the set function, each individual character in the
string becomes a member of the set. Here is an example: myset = set('abc') After this
statement executes, the myset variable will reference a set containing the elements 'a',
'b', and 'c'.
Creating Sets
• 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.
Here is an example: myset = set('aaabc') The character 'a' appears multiple times in the
string, but it will appear only once in the set. After this statement executes, the myset
variable will reference a set containing the elements 'a', 'b', and 'c’.
• # This is an ERROR! myset = set('one', 'two', 'three’) because you can pass no more than
one argument to the set function.
• # OK, this works. myset = set(['one', 'two', 'three']) After this statement executes, the
myset variable will reference a set containing the elements 'one', 'two', and 'three'.
Getting the Number of Elements in a Set
• you can use the len function to get the number of elements in a set.
Adding and Removing Elements
• Sets are mutable objects, so you can add items to them and remove items from them.
• You can use the for loop in the following general format to iterate over all the elements
in a set:
for var in set:
statement
statement
etc.
Using the in and not in Operators to Test for a Value
in a Set
Finding the Union of Sets
• The union of two sets is a set that contains all the elements of both sets. In Python, you
can call the union method to get the union of two sets. Here is the general format:
set1.union(set2)
• You can also use the | operator to find the union of two sets.
Finding the Intersection of Sets
• The intersection of two sets is a set that contains only the elements that are found in both
sets. Here is the general format:
set1.intersection(set2)
• You can also use the & operator to find the intersection of two sets.
Finding the Difference of Sets
• The difference of set1 and set2 is the elements that appear in set1 but do not appear in
set2. Here is the general format:
set1.difference(set2)
You can also use the − operator to find the difference of two sets.
Finding the Symmetric Difference of Sets
• The symmetric difference of two sets is a set that contains the elements that are not
shared by the sets. In other words, it is the elements that are in one set but not in both.
• In Python, you can call the symmetric_difference method to get the symmetric difference
of two sets. Here is the general format:
set1.symmetric_difference(set2)
You can also use the ˆ operator to find the symmetric difference of two sets.
Finding Subsets and Supersets
• set1 = set([1, 2, 3, 4]) set2 = set([2, 3])
• In this example, set1 contains all the elements of set2, which means that set2 is a subset
of set1. It also means that set1 is a superset of set2.
• set2.issubset(set1) In the general format, set1 and set2 are sets. The method returns
True if set2 is a subset of set1. Otherwise, it returns False. You can call the issuperset
method to determine whether one set is a superset of another. Here is the general format:
set1.issuperset(set2)
Finding Subsets and Supersets
• You can also use the <= operator to determine whether one set is a subset of another
and the >= operator to determine whether one set is a superset of another. Here is the
general format of an expression using the <= operator with two sets: set2 <= set1 In the
general format, set1 and set2 are sets. The expression returns True if set2 is a subset of
set1. Otherwise, it returns False. Here is the general format of an expression using the >=
operator with two sets: set1 >= set2
End