Professional Documents
Culture Documents
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:
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:
Changing dictionaries
Let’s start with this dictionary:
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:
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:
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:
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:
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:
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.
dictionary_name.get(key)
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'
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.
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'}
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'>
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)
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
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.
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
d) Print out the (key-value) pairs sorted by the number of days in each month