You are on page 1of 10

FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Lab-09
Dictionary and Set in Python
Objectives:
The purpose of this lab is to get you familiar with the operations related Dictionary
and Set data type in Python.

Apparatus:
Hardware Requirement
Personal computer.
Software Requirement
Anaconda, Jupyter Notebook/ Spyder

Theory:
Dictionaries
A dictionary is a more general version of a list. Here is a list that contains the
number of days in the months of the year:
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
If we want the the number of days in January, use days[0]. December is days[11]
or days[-1]. Here is a dictionary of the days in the months of the year:

To get the number of days in January, we use days['January'].

One benefit of using dictionaries here is the code is more readable, and we don’t
have to figure out which index in the list a given month is at. Dictionaries have a number of other
uses, as well.

Creating dictionaries
Here is a simple dictionary:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a


pair separated by a colon. The first part of the pair is called the key and the second is the value.
The key acts like an index. So in the first pair, 'A':100, the key is 'A', the value is 100, and d['A']
gives 100. Keys are often strings, but they can be integers, floats, and many other things as well.
You can mix different types of keys in the same dictionary and different types of values, too.

Changing dictionaries
Let’s start with this dictionary:

To change d['A'] to 400, do


d['A']=400
To add a new entry to the dictionary, we can just assign it, like below:
d['C']=500

Example:

Note that this sort of thing does not work with lists. Doing L[2]=500 on a list with
two elements would produce an index out of range error. But it does work with dictionaries.
To delete an entry from a dictionary, use the del operator:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Empty dictionary
The empty dictionary is {}, which is the dictionary equivalent of [] for lists or '' for
strings.

Important note
The order of items in a dictionary will not necessarily be the order in which put
them into the dictionary. Internally, Python rearranges things in a dictionary in order to optimize
performance.

Dictionary examples
Example 1
You can use a dictionary as an actual dictionary of definitions:

Here is an example of the dictionary in use:

Example 2
The following dictionary is useful in a program that works with Roman numerals.

Example 3
In the game Scrabble, each letter has a point value associated with it. We can use
the following dictionary for the letter values:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

To score a word, we can do the following:

Working with dictionaries


Copying dictionaries
Just like for lists, making copies of dictionaries is a little tricky for reasons we will
cover later. To copy a dictionary, use its copy method. Here is an example:

in
The in operator is used to tell if something is a key in the dictionary. For instance,
say we have the following dictionary:

Referring to a key that is not in the dictionary will produce an error. For instance,
print(d['C']) will fail. To prevent this error, we can use the in operator to check first if a key is in
the dictionary before trying to use the key. Here is an example:

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

You can also use not in to see if a key is not in the dictionary

Looping
Looping through dictionaries is similar to looping through lists. Here is an example
that prints the keys in a dictionary:

Here is an example that prints the values:

dict
The dict function is another way to create a dictionary. One use for it is kind of
like the opposite of the items method:
d = dict([('A',100),('B',300)])
This creates the dictionary {'A':100,'B':300}. This way of building a dictionary is
useful if your program needs to construct a dictionary while it is running.

Methods of Dictionary:
Methods that are available with a dictionary are tabulated below.
 get()  gives the value of the given key.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

dictionary_name.get(key)

 values()  gives all the values in a dictionary.


dictionary_name.values()

 items()  gives all the keys and values as pairs.


dictionary_name.items()

 clear() empty the dictionary by removing all items


dictionary_name.clear()

 keys()gives all the keys in a dictionary.


dictionary_name.keys()

 pop() removes the value of the given key from the dictionary.
dictionary_name.pop(key)
Examples
Dict1={'a': "apple", 'b': "banana", 'c': "cat"}
print(Dict1.get('a') # 'apple'
print(Dict1.values()) # dict_values(['apple', 'banana', 'cat'])
print(Dict1.items()) # dict_items([('a', 'apple'), ('b', 'banana'), ('c', 'cat')])
print(Dict1.clear())# #{}
print(Dict1.keys()) #dict_keys(['a', 'b', 'c'])
print(Dict1.pop('b')) #'banana'

Lists of keys and values


The following examples illustrates the ways to get lists of keys and values from a
dictionary. It uses the dictionary d={'A':1,'B':3}.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Set:
A set is an unordered collection of items. Every set element is unique (no
duplicates) and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {},
separated by comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.

Example:
# Different types of sets in Python
my_set = {1, 2, 3} # set of integers
print(my_set) #{1, 2, 3}
my_set = {1.0, "Hello", (1, 2, 3)} # set of mixed datatypes
print(my_set) #{1.0, (1, 2, 3), 'Hello'}

Creating an empty set is a bit tricky.


Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements, we use the set() function without any argument.

Example:
# Distinguish set and dictionary while creating empty set
a = {} # initialize a with {}
print(type(a)) # check data type of a  <class 'dict'>
a = set() # initialize a with set()
print(type(a)) # check data type of a  <class 'set'>

Modifying a set in Python


Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it. We can add a single element using the add() method, and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its argument.
In all cases, duplicates are avoided.

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

Example:
my_set = {1, 3} # initialize my_set
print(my_set)
my_set[0] # TypeError: 'set' object does not support indexing
my_set.add(2) # Output: {1, 2, 3}
print(my_set)
my_set.update([2, 3, 4]) # add multiple elements Output: {1, 2, 3, 4}
print(my_set)

Removing elements from a set


A particular item can be removed from a set using the methods discard() and
remove(). The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set. On the other hand, the remove() function will
raise an error in such a condition (if element is not present in the set).

Example:
# Difference between discard() and remove()
my_set = {1, 3, 4, 5, 6} # initialize my_set
my_set.discard(4) # discard an element
print(my_set) #Output: {1, 3, 5, 6}
my_set.remove(6) # remove an element
print(my_set) # Output: {1, 3, 5}
my_set.discard(2) # discard an element(not present in my_set)
print(my_set) # Output: {1, 3, 5}
my_set.remove(2) # remove an element( not present in my_set) 
Output: KeyError

Python Set Methods


There are many set methods, some of which we have already used above. Here is a
list of all the methods that are available with the set objects:
 add()  Adds an element to the set
 clear() Removes all elements from the set
 copy() Returns a copy of the set
 difference()  Returns the difference of two or more sets as a new set
 difference_update()  Removes all elements of another set from this set
 discard()  Removes an element from the set if it is a member. (Do nothing if
the element is not in set)
 intersection()  Returns the intersection of two sets as a new set
 intersection_update() Updates the set with the intersection of itself and
another

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

 isdisjoint() Returns True if two sets have a null intersection


 issubset() Returns True if another set contains this set
 issuperset()  Returns True if this set contains another set
 pop() Removes and returns an arbitrary set element. Raises KeyError if the
set is empty
 remove() Removes an element from the set. If the element is not a member,
raises a KeyError
 symmetric_difference()  Returns the symmetric difference of two sets as a
new set
 symmetric_difference_update() Updates a set with the symmetric difference
of itself and another
 union() Returns the union of sets in a new set
 update() Updates the set with the union of itself and others

Exercises
1. Write a program to print the age of a student if student name is given by user as
input. You can hardcoded three students name and age in dictionary.

2. Write a program to print subject names and marks of three subjects. Take input
from user subject names and marks and store them in a dictionary.

3. Remove duplicate from a list and create a tuple and find the minimum and
maximum number.

4. How is the intersection and union operation of two sets obtained?

5. Difference between sets and lists

6. Write a program that repeatedly asks the user to enter product names and prices.
Store all of these in a dictionary whose keys are the product names and whose
values are the prices. When the user is done entering products and prices, allow
them to repeatedly enter a product name and print the corresponding price or a
message if the product is not in the dictionary.

7. Using the dictionary created in the previous problem, allow the user to enter a
dollar amount and print out all the products whose price is less than that amount.

8. For this problem, use the dictionary from the beginning of this chapter whose keys
are month names and whose values are the number of days in the corresponding
months.

a) Ask the user to enter a month name and use the dictionary to tell them how

IQRA University, North Campus, Karachi


FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY

many days are in the month.

b) Print out all of the keys in alphabetical order.

c) Print out all of the months with 31 days.

d) Print out the (key-value) pairs sorted by the number of days in each month

IQRA University, North Campus, Karachi

You might also like