0% found this document useful (0 votes)
36 views32 pages

Lecture 5 - 1

Uploaded by

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

Lecture 5 - 1

Uploaded by

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

SCIENTIFIC PROGRAMMING

(CSC231)
CHAPTER 4: THE CORE PYTHON LANGUAGE
II

J. D. Akinyemi (Ph.D.)
Department of Computer Science,
University of Ibadan, Ibadan, Nigeria
OUTLINE

1. Python Objects III: Dictionaries and Sets


1. Dictionaries
1. Defining and Indexing a Dictionary
2. Dictionary Methods
2. Sets

2
DICTIONARIES
• A dictionary in Python is a type of “associative array” (also known as a “hash” in
some languages).
• A dictionary can contain any objects as its values
• Unlike sequences such as lists and tuples, in which the items are indexed by an
integer starting at 0,
• Each item in a dictionary is indexed by a unique key, which may be any
immutable object.
• The dictionary therefore exists as a collection of key-value pairs;
• dictionaries themselves are mutable objects.

3
DICTIONARIES
• Defining and Indexing Dictionaries
• An dictionary can be defined by giving key-value pairs between curly braces {}:
>>> height = {'Burj Khalifa': 828., 'One World Trade Center': 541.3,
'Mercury City Tower': -1., 'Q1': 323.,
'Carlton Centre': 223., 'Gran Torre Santiago': 300.,
'Mercury City Tower': 339.}
>>> height
{'Burj Khalifa': 828.0,
'One World Trade Center': 541.3,
'Mercury City Tower': 339.0,
'Q1': 323.0,
'Carlton Centre': 223.0,
'Gran Torre Santiago': 300.0}

4
DICTIONARIES
• Defining and Indexing Dictionaries
• The command print(height) will return the dictionary in the same format (between braces).
• If the same key is attached to different values (as 'Mercury City Tower' is here), only the
most recent value survives: the keys in a dictionary are unique.
• Before Python 3.6, the items in a dictionary were not guaranteed to have any particular order;
• Since Python 3.6, the order of insertion is preserved.
• Note that as in the example above, redefining the value attached to a key does not change the
key’s insertion order:
• The key 'Mercury City Tower' is the third key to be defined, where it is given the value -1.
• It is later reassigned the value 339, but still appears in third position when the dictionary is
used.

5
DICTIONARIES
• Defining and Indexing Dictionaries
• An individual item can be retrieved by indexing it with its key, either as a literal
or with a variable equal to the key:
>>> height['One World Trade Center']
541.3
>>> building = 'Carlton Centre'
>>> height[building]
223.0

• Items in a dictionary can also be assigned by indexing it in this way:


height['Empire State Building'] = 381.
height['The Shard'] = 306.

6
DICTIONARIES
• Defining and Indexing Dictionaries
• An alternative way of defining a dictionary is to pass a sequence of (key, value)
pairs to the dict constructor.
• If the keys are simple strings (of the sort that could be used as variable names),
the pairs can also be specified as keyword arguments to this constructor:
>>> ordinal = dict([(1, 'First'), (2, 'Second'), (3, 'Third')])
>>> mass = dict(Mercury=3.301e23, Venus=4.867e24, Earth=5.972e24)
>>> ordinal[2] # NB 2 here is a key, not an index
'Second'
>>> mass['Earth']
5.972e+24

7
DICTIONARIES
• Defining and Indexing Dictionaries
• A for-loop iteration over a dictionary returns the dictionary keys (in order of key
insertion):
for c in ordinal:
print(c, ordinal[c])

1 First
2 Second
3 Third

8
DICTIONARIES
• Defining and Indexing Dictionaries

9
DICTIONARIES
• Dictionary Methods: get()
• Indexing a dictionary with a key that does not exist is an error:
>>> mass['Pluto']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Pluto'

• However, the useful method get() can be used to retrieve the value, given a key
if it exists, or some default value if it does not.
• If no default is specified, then None is returned.
>>> print(mass.get('Pluto'))
None
>>> mass.get('Pluto', -1)
-1

10
DICTIONARIES
• Dictionary Methods: keys(), values(), items()
• The three methods, keys, values and items, return, respectively, a
dictionary’s keys, values and key-value pairs (as tuples).
• In previous versions of Python, each of these were returned in a list, but for most
purposes this is wasteful of memory:
• Python 3 solves this by returning an iterable object, which accesses the
dictionary’s keys one by one, without copying them to a list.
• This is faster and saves memory (important for very large dictionaries).

11
DICTIONARIES
• Dictionary Methods: keys(), values(), items()
>>> planets = mass.keys()
>>> print(planets)
dict_keys(['Mercury', 'Venus', 'Earth'])
>>> for planet in planets:
... print(planet , mass[planet])
...
Mercury 3.301e+23
Venus 4.867e+24
Earth 5.972e+24

• A dict_keys object can be iterated over any number of times, but it is not a list and cannot be
indexed or assigned:
>>> planets = mass.keys()
>>> planets[0]
Traceback (most recent call last):
File "<stdin >", line 1, in <module >
TypeError: 'dict_keys' object is not subscriptable

12
DICTIONARIES
• Dictionary Methods: keys(), values(), items()
• If you really do want a list of the dictionary’s keys, simply pass the dict_keys object to the list
constructor (which takes any kind of sequence and makes a list out of it):
>>> planet_list = list(mass.keys())
>>> planet_list
['Mercury', 'Venus', 'Earth']
>>> planet_list[0]
'Mercury'
>>> planet_list[1] = 'Jupiter'
>>> planet_list
['Mercury', 'Jupiter', 'Earth']

• This last assignment only changes the planet_list list; it doesn’t alter the original dictionary’s
keys.

13
DICTIONARIES
• Dictionary Methods: keys(), values(), items()
• Similar methods exist for retrieving a dictionary’s values and items (key-value pairs): the objects
returned are dict_values and dict_items.
>>> mass.items()
dict_items([('Mercury', 3.301e+23), ('Venus', 4.867e+24), ('Earth', 5.972e+24)])
>>> mass.values()
dict_values ([3.301e+23, 4.867e+24, 5.972e+24])
>>> for planet_data in mass.items():
... print(planet_data)
...
('Mercury', 3.301e+23)
('Venus', 4.867e+24)
('Earth', 5.972e+24)

14
DICTIONARIES
• Keyword Arguments
• In Section 2.7, we discussed the syntax for passing arguments to functions.
• In that description, it was assumed that the function would always know what arguments could be
passed to it and these were listed in the function definition.
• For example,
def func(a, b, c):
• Python provides a couple of useful features for handling the case where it is not necessarily
known what arguments a function will receive.
• Including *args (after any “formally defined” arguments) places any additional positional
argument into a tuple, args, as illustrated by the following code:

15
DICTIONARIES
• Keyword Arguments
>>> def func(a, b, *args):
... print(args)
...
>>> func(1, 2, 3, 4, 'msg')
(3, 4, 'msg')

• That is, inside func, in addition to the formal arguments a=1 and b=2, the
arguments 3, 4 and 'msg' are available as the items of the tuple args (This tuple
can be arbitrarily long).
• Python’s own print built-in function works in this way: it takes an arbitrary
number of arguments to output as a string, followed by some optional keyword
arguments:
def print(*args , sep=' ', end='\n', file=None):

16
DICTIONARIES
• Keyword Arguments
• One can also use *args and **kwargs when calling a function, which can be convenient,
for example, with functions that take a large number of arguments:
>>> def func(a, b, c, x, y, z):
... print(a, b, c)
... print(x, y, z)
...
>>> args = [1, 2, 3]
>>> kwargs = {'x': 4, 'y': 5, 'z': 'msg'}
>>> func(*args , **kwargs)
1 2 3
4 5 msg

17
DICTIONARIES
• default_dict
• With regular Python dictionaries, an attempt to retrieve a value using a key that
does not exist will raise a KeyError exception.
• There is a useful container, called defaultdict, that subclasses the dict built-in.
• defaultdict allows one to specify default_factory, a function which returns the
default value to be assigned to the key if it is missing.

18
DICTIONARIES

19
DICTIONARIES

20
SETS
• A set is an unordered collection of unique items.
• As with dictionary keys, elements of a set must be hashable objects.
• A set is useful for removing duplicates from a sequence and for determining the
union, intersection and difference between two collections.
• Because they are unordered, set objects cannot be indexed or sliced, but they can
be iterated over, tested for membership and they support the len built-in.
• A set is created by
• listing its elements between braces ({...}) or
• passing an iterable to the set() constructor:

21
SETS
>>> s = set([1, 1, 4, 3, 2, 2, 3, 4, 1, 3, 'surprise!'])
>>> s
{1, 2, 'surprise!', 3, 4}
>>> len(s) # cardinality of the set
5
>>> 2 in s, 6 not in s # membership , nonmembership
(True , True)
>>> for item in s:
... print(item)
...
1
2
surprise!
3
4

22
SETS
• The set method add is used to add elements to the set.
• To remove elements there are several methods:
• remove removes a specified element but raises a KeyError exception if the element
is not present in the set.
• discard does the same but does not raise an error in this case.
• Both methods take (as a single argument) the element to be removed.
• pop (with no argument) removes and returns an arbitrary element from the set
• clear removes all elements from the set:

23
SETS
>>> s = {2,-2,0}
>>> s.add(1)
>>> s.add(-1)
>>> s.add(1.0) # 1 == 1.0 is True, so 1.0 is not added to the set
>>> s
{0, 1, 2, -1, -2}
>>> s.remove(1)
>>> s
{0, 2, -1, -2}
>>> s.discard(3) # OK - does nothing
>>> s
{0, 2, -1, -2}
>>> s.pop()
0 # (for example)
>>> s
{2, -1, -2}
>>> s.clear()
set() # the empty set

24
SETS
objects have a wide range of methods corresponding to the properties of
• set
mathematical sets;
• The most useful are illustrated in Table 4.2, which uses the following terms from set
theory:
• The cardinality of a set, |A|, is the number of elements it contains.
• Two sets are equal if they both contain the same elements.
• Set A is a subset of set B (A ⊆ B) if all the elements of A are also elements of B; set B is said to be a superset
of set A.
• Set A is a proper subset of B (A ⊂ B) if it is a subset of B but not equal to B; in this case, set B is said to be a
proper superset of A.
• The union of two sets (A ∪ B) is the set of all elements from both of them.
• The intersection of two sets (A ∩ B) is the set of all elements they have in common.
• The difference of set A and set B (A \ B) is the set of elements in A that are not in B.
• The symmetric difference of two sets, A ∆ B, is the set of elements in either but not in both.
• Two sets are said to be disjoint if they have no elements in common.

25
SETS

26
SETS
• As seen from table 4.2, there are two forms for most set expressions:
• the operator-like syntax requires all arguments to be set objects,
• whereas explicit method calls will convert any iterable argument into a set.
>>> A = set((1, 2, 3))
>>> B = set((1, 2, 3, 4))
>>> A <= B
True
>>> A.issubset((1, 2, 3, 4)) # OK: (1, 2, 3, 4) is turned into a set
True

27
SETS
Some more examples:
>>> C, D = set((3, 4, 5, 6)), set((7, 8, 9))
>>> B | C # union
{1, 2, 3, 4, 5, 6}
>>> A | C | D # union of three sets
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> A & C # intersection
{3}
>>> C & D
set() # the empty set
>>> C.isdisjoint(D)
True
>>> B - C # difference
{1, 2}
>>> B ^ C # symmetric difference
{1, 2, 5, 6}

28
SETS
• frozensets
• sets are mutable objects (items can be added to and removed from a
set),
• because of this they are unhashable and so cannot be used as
dictionary keys or as members of other sets.
>>> a = set((1, 2, 3))
>>> b = set(('q', (1, 2), a))
Traceback (most recent call last):
File "<stdin >", line 1, in <module>
TypeError: unhashable type: 'set'

29
SETS
• frozensets
• (In the same way, lists cannot be dictionary keys or set members.)
• There is, however, a frozenset object which is a kind of immutable
(and hashable) set.
• frozensets are fixed, unordered collections of unique objects and can
be used as dictionary keys and set members.
>>> a = frozenset((1, 2, 3))
>>> b = set(('q', (1, 2), a)) # OK: the frozenset a is hashable
>>> b.add(4) # OK: b is a regular set
>>> a.add(4) # not OK: frozensets are immutable
Traceback (most recent call last):
File "<stdin >", line 1, in <module >
AttributeError: 'frozenset' object has no attribute 'add'

30
EXERCISES

31
REFERENCE TEXTS AND ONLINE RESOURCES
• Scientific Programming in Python
1. ** Christian Hill. Learn Scientific Programming with Python. 2nd edition, 2020.
Cambridge Press
2. Hans Petter Langtangen. A Primer on Scientific Prorgramming with Python. 4th edition
2014.
3. Robert Johansson. Numerical Python: Scientific Computing and Data Science
Applications with Numpy, Scipy and Matplotlib. 2nd edition. 2019. Apress.

• Python Basics
4. Finxter: https://app.finxter.com/learn/computer/science/ (Here, you will have fun while
you learn with python code puzzles)
5. Data Camp: https://www.datacamp.com/courses/intro-to-python-for-data-science

32

You might also like