Previous - Next

Sets and Dictionaries

Sets

We can define sets in Python, which resemble the set theory from mathematics. Sets are simple types but are expensive to use and they can slow down the program because of their time-consuming operations for the CPU. To construct a set, one can use the set() function to do so, which can also optionally receive arguments.

L = [1,2,3,4,4]
S = set(L)
T = {3,4,5,6} 

Sets do not have orders and do not allow repeated elements. For example, the set S above only contains 1,2,3,4 in no particular order. One can add values to a set or pop an arbitrary value from a set. When popping from a set, an element is deleted from the set and is returned as a value, which can be either used in an expression or stored in a variable. Note that we cannot add lists, tuples, or sets to a set. When working on sets, we often store numbers or strings in them. Also, because there is no order in a set, we cannot use indexing with sets.

T.add(7)
x = T.pop()

Standard set operations are available for Python sets. One can intersect or union two sets. It's also possible to compute the difference between two sets.

A = T & S #T.intersection(S)
B = T | S #T.union(S)
C = T - S #T.difference(S)
D = T ^ S #T.symmetric_difference(S)

Here is the description of these operations:

Each of the three basic set operations can either be done using an operator (&, |, -, ^) or using a corresponding set method. Try the operations above and see the elements that are stored in A, B, and C.

Dictionaries

A dictionary is a type that can hold multiple items of key and value pairs. Each item in a dictionary has a key that can be a string (or some other types) and a corresponding value that can be of any type. Dictionaries can be best explained using an example. Suppose that we would like to construct a dictionary to hold the records of a student, including name, GPA, current courses, major, and the number of credits passed so far.

student = dict() 
student['name']    = 'Ahmad'
student['GPA']     = 3.7
student['courses'] = {111,126,201,301}
student['major']   = 'Mathematics' 
student['credits'] = 60 

The dictionary above has five items of keys and values. We can similarly add more. We can also delete an item by using the del operator followed by the dictionary name and a valid key. We could also write a for loop that iterates over all the items in a dictionary.

for key, value in student.items():
   print(key,':',value)