[go: up one dir, main page]

0% found this document useful (0 votes)
18 views105 pages

Lec 5

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)
18 views105 pages

Lec 5

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/ 105

LEARNING OBJECTIVES

1. Understand Tuples
2. Understand Lists
3. Contrast Tuples and Lists
4. Dictionaries; de ning, keys, values,
iterating, operations

1
fi
COMPOUND DATA TYPES

Have seen simple data types:


◦ int, float, bool, string
Compound data types
◦ Tuples, lists, ...
◦ Made up of other data types: e.g., ints, floats,
bools, strings
◦ Can be arbitrary data types
◦ Can mix and match different data types in the
same compound data type

2
◼︎
◼︎
TUPLES

An ordered sequence of elements of arbitrary type


Cannot change element values: immutable
Represented with parentheses (can be omitted)
t = () assign t to empty tuple
t = (2, "rhul", 3)
t[0] ➔ evaluates to 2
(2, "rhul", 3) + (5, 6) ➔ evaluates to (2, "rhul", 3, 5, 6)
t[1:2] ➔ evaluates to ("rhul",)
t[1:3] ➔ evaluates to ("rhul", 3)
len(t) ➔ evaluates to 3
t[1] = 4 ➔ error - tuples are immutable
3
◼︎
◼︎
◼︎
TUPLES

An ordered sequence of elements of arbitrary type


Cannot change element values: immutable
Represented with parentheses (can be omitted)
t = () assign t to empty tuple
t = (2, "rhul", 3)
t[0] ➔ evaluates to 2
(2, "rhul", 3) + (5, 6) ➔ evaluates to (2, "rhul", 3, 5, 6)
t[1:2] ➔ evaluates to ("rhul",) extra comma
means a tuple
with one element
t[1:3] ➔ evaluates to ("rhul", 3)
len(t) ➔ evaluates to 3
t[1] = 4 ➔ error - tuples are immutable
3
◼︎
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y
y = x

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y
y = x

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x
y = x x = y
y = tmp

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x
y = x x = y
y = tmp

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x (x, y) = (y, x)


y = x x = y
y = tmp

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x (x, y) = (y, x)


y = x x = y
y = tmp

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x (x, y) = (y, x) x, y = y, x


y = x x = y
y = tmp

4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values

x = y tmp = x (x, y) = (y, x) x, y = y, x


y = x x = y
y = tmp

4
◼︎
◼︎
MULTIPLE RETURN VALUES

Can be used to return more than one value from


a function
def quotient_and_remainder(x, y):
q = x // y
r = x % y
return (q, r)

(quot, rem) = quotient_and_remainder(5,3)


print(quot)
print(rem)
5
◼︎
MULTIPLE RETURN VALUES

Can be used to return more than one value from


a function
def quotient_and_remainder(x, y):
q = x // y
r = x % y
return (q, r)

(quot, rem) = quotient_and_remainder(5,3)


print(quot)
print(rem)
5
◼︎
MULTIPLE RETURN VALUES

Can be used to return more than one value from


a function
def quotient_and_remainder(x, y):
q = x // y
r = x % y
return (q, r)

(quot, rem) = quotient_and_remainder(5,3)


print(quot)
print(rem)
5
◼︎
MANIPULATING TUPLES
aTuple = ((1,"a"),(2, "b"), ... )

def get_data(aTuple):
nums = () # empty tuple
words = ()
for t in aTuple:
# concatenating with a singleton tuple
nums = nums + (t[0],)
# only add words haven't added before
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums)
max_n = max(nums)
unique_words = len(words)
return (min_n, max_n, unique_words)
6
CHECK YOURSELF!

What does always_sunny(('cloudy'), ('cold',))


evaluate to?

def always_sunny(t1, t2): 1. ('sunny', 'cc')


""" 2. ('sunny', 'ccold')
t1, t2 are non empty
3. ('sunny', 'cloudycold')
"""
sun = ("sunny","sun")
first = t1[0] + t2[0]
return (sun[0], first)

7
Moodle quiz ‘Tuples’

8
LISTS

Ordered sequence of data, accessible by index


A list is denoted by square brackets, []
A list contains elements
◦ usually homogeneous (i.e., all integers)
◦ can contain mixed types
A list is mutable:
◦ List elements can be changed in place

9
◼︎
◼︎
◼︎
◼︎
LIST INDEXING
a_list = [] assign a_list to empty list
L = [2, 'a', 4, [1, 2]]
len(L) ➔ evaluates to 4
L[0] ➔ evaluates to 2
L[2]+1 ➔ evaluates to 5
L[3] ➔ evaluates to [1, 2]
L[4] ➔ error (out of range)

i = 2
L[i-1] ➔ evaluates to 'a' since L[1]='a' above

10
CHANGING ELEMENTS

Lists are mutable


Assigning to an element at an index changes the
CHANGING
value ELEMENTS
L =
lists are [2, 1,
mutable! 3]
assigning to an element at an index changes the value
L[1] = 5
L = [2, 1, 3]
L is= now
L[1] 5 [2, 5, 3], no new object is created!
L is now [2, 5, 3], note this is the same object L

[2,1,3]
[2,5,3]

L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS

Lists are mutable


Assigning to an element at an index changes the
CHANGING
value ELEMENTS
L =
lists are [2, 1,
mutable! 3]
assigning to an element at an index changes the value
L[1] = 5
L = [2, 1, 3]
L is= now
L[1] 5 [2, 5, 3], no new object is created!
L is now [2, 5, 3], note this is the same object L

[2,1,3]
[2,5,3]

L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS

Lists are mutable


Assigning to an element at an index changes the
CHANGING
value ELEMENTS
L =
lists are [2, 1,
mutable! 3]
assigning to an element at an index changes the value
L[1] = 5
L = [2, 1, 3]
L is= now
L[1] 5 [2, 5, 3], no new object is created!
L is now [2, 5, 3], note this is the same object L

[2,1,3]
[2,5,3]

L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS

Lists are mutable


Assigning to an element at an index changes the
CHANGING
value ELEMENTS
L =
lists are [2, 1,
mutable! 3]
assigning to an element at an index changes the value
L[1] = 5
L = [2, 1, 3]
L is= now
L[1] 5 [2, 5, 3], no new object is created!
L is now [2, 5, 3], note this is the same object L

[2,1,3]
[2,5,3]

L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
Moodle quiz ‘Lists 1’

12
ITERATING OVER A LIST

Compute the sum of elements of a list


Common iteration patterns:

total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)

13
◼︎
◼︎
ITERATING OVER A LIST

Compute the sum of elements of a list


Common iteration patterns:

total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)

List elements are indexed


from 0 to len(L) - 1

13
◼︎
◼︎
ITERATING OVER A LIST

Compute the sum of elements of a list


Common iteration patterns:

total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)

List elements are indexed Lists are iterable,


from 0 to len(L) - 1 just as strings and tuples

13
◼︎
◼︎
OPERATIONS ON LISTS: ADD

Add elements to end of list with


L.append(element)
Mutates the list!
L = [2, 1, 3]
L.append(5) ➔ L is now [2, 1, 3, 5]

14
◼︎
◼︎
OPERATIONS ON LISTS: ADD

Add elements to end of list with


L.append(element)
Mutates the list!
L = [2, 1, 3]
L.append(5) ➔ L is now [2, 1, 3, 5]

14
◼︎
◼︎
OPERATIONS ON LISTS: ADD

Add elements to end of list with


L.append(element)
Mutates the list!
L = [2, 1, 3]
L.append(5) ➔ L is now [2, 1, 3, 5]

What is a dot?
• lists are Python objects, everything in Python is an object
• objects have data
• objects have methods and functions
• access this information by object_name.do_something()
• will learn more about these later

14
◼︎
◼︎
OPERATIONS ON LISTS: ADD

To combine lists together use concatenation, +


operator
◦ Creates a new list
Extend list "in place" with L.extend(some_list)
◦ Mutates the list
L1 = [2, 1, 3]
L2 = [4, 5, 6]
L3 = L1 + L2 ➔ L3 is [2, 1, 3, 4, 5, 6]
L1, L2 unchanged

L1.extend([0, 6]) ➔ Mutated L1 to [2, 1, 3, 0, 6]


15
◼︎
◼︎
OPERATIONS ON LISTS: REMOVE

del(L[index]): Delete element at a specific index


L.pop(): Remove element at the end of list with,
returns the removed element
◦ L.pop(i): remove and return element at index i
L.remove(element): remove the first occurrence
of a specific element, error if element not in list
L = [2,1,3,6,3,7,0] # do commands below in order
L.remove(2) ➔ mutates L=[1,3,6,3,7,0]
L.remove(3) ➔ mutates L=[1,6,3,7,0]
del(L[1]) ➔ mutates L=[1,3,7,0]
L.pop() ➔ mutates L=[1,3,7]
16
◼︎
◼︎
◼︎
OPERATIONS ON LISTS: REMOVE

del(L[index]): Delete element at a specific index


L.pop(): Remove element at the end of list with,
returns the removed element
◦ L.pop(i): remove and return element at index i
L.remove(element): remove the first occurrence
of a specific element, error if element not in list
L = [2,1,3,6,3,7,0] # do commands below in order
L.remove(2) ➔ mutates L=[1,3,6,3,7,0]
L.remove(3) ➔ mutates L=[1,6,3,7,0] all operations
del(L[1]) ➔ mutates L=[1,3,7,0] mutate the list!
L.pop() ➔ mutates L=[1,3,7]
16
◼︎
◼︎
◼︎
CONVERT LISTS TO STRINGS

'<string>'.join(L): convert list of strings into


a string
◦ <string> is added between every element

L = ['a','bc','d','ef'] ➔ L is a list
''.join(L) ➔ returns 'abcdef'
'_'.join(L) ➔ returns 'a_bc_d_ef'
'XYZ'.join(L) ➔ returns 'aXYZbcXYZdXYZef'

17
◼︎
Moodle quiz ‘Lists 2’

18
CONVERT STRINGS TO LISTS

list(s): convert string to list, returns a list L


with every character from s an element in L
s.split(<string>): split a string on a string
parameter, splits on spaces if called without a
parameter

s = "I<3 cs" ➔ s is a string


list(s) ➔ returns ['I','<',' ','c','s']
s.split('<') ➔ returns ['I', '3 cs']

19
◼︎
◼︎
OTHER LIST OPERATIONS

sort() and sorted()

L = [9,6,0,3]
sorted(L) ➔ returns sorted list, does not mutate L
L.sort() ➔ mutates L = [3, 0, 6, 9]
L.reverse() ➔ mutates L = [9, 6, 3, 0]

Many more:
https://docs.python.org/3/tutorial/
datastructures.html

20
◼︎
◼︎
LISTS IN MEMORY

21
LISTS IN MEMORY

List is an object in memory

21
◼︎
LISTS IN MEMORY

List is an object in memory


Variable name points to object

21
◼︎
◼︎
LISTS IN MEMORY

List is an object in memory


Variable name points to object
Multiple variables can point to the same object
(aliasing)

21
◼︎
◼︎
◼︎
LISTS IN MEMORY

List is an object in memory


Variable name points to object
Multiple variables can point to the same object
(aliasing)
Mutability and aliasing lead to subtle side-effects

21
◼︎
◼︎
◼︎
◼︎
LISTS IN MEMORY

List is an object in memory


Variable name points to object
Multiple variables can point to the same object
(aliasing)
Mutability and aliasing lead to subtle side-effects
◦ Any variable pointing to the same object is affected
by mutations

21
◼︎
◼︎
◼︎
◼︎
LISTS IN MEMORY

List is an object in memory


Variable name points to object
Multiple variables can point to the same object
(aliasing)
Mutability and aliasing lead to subtle side-effects
◦ Any variable pointing to the same object is affected
by mutations
Be aware of side-effects when working with lists!

21
◼︎
◼︎
◼︎
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes
hot is an alias for warm – changing one changes
the
other!
the other!
append()
append() has ahas a side
side effect
effect

22
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes the
ALIASES
other!

hot append()
is an has
alias a
for side
warm effect
– changing one changes the
hot is an alias for warm – changing one changes
other!
the other!
append()
append() has ahas a side
side effect
effect

6.0001 LECTURE 5 19

22
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes the
ALIASES
other!

hot append()
is an has
alias a
for side
warm effect
– changing one changes the
hot is an alias for warm – changing one changes
other!
the other!
ALIASES
append()
append() has ahas a side
side effect
effect
hot is an alias for warm – changing one changes the
other!
append() has a side effect
6.0001 LECTURE 5 19

22
◼︎
◼︎
Moodle quiz ‘Lists 3’

23
CLONING
CLONING A LIST
A LIST
create a new list and copy every element using
chill
Create = cool[:]
a new list and copy every element using
chill = cool[:]

6.0001 LECTURE 5 20
24
◼︎
CLONING
CLONING A LIST
A LIST
create a new list and copy every element using
GA chill
Create
LIST =
a newcool[:]
list and copy every element using
chill = cool[:]
st and copy every element using
ol[:]

6.0001 LECTURE 5 20
6.0001 LECTURE 5 2024
◼︎
CLONING
CLONING A ALIST
A LIST
CLONING LIST
create a new
create listlist
a new andand
copy every
copy element
every using
element using
GA chill
Create
LIST chill =
a new cool[:]
=list and copy every element using
cool[:]
chill = cool[:]
st and copy every element using
ol[:]

6.0001 LECTURE 5
6.0001 LECTURE 5 20 20
6.0001 LECTURE 5 2024
◼︎
calling sorted()
does not mutate
sort()
list, mustAND
assignsorted()
result to a variable

6.0001 LECTURE 5

25
sorted()
callingcalling sort() mutates the list, returns nothing
does not mutate
calling sorted()
sort() AND
does
list, must sorted()
not mutate
assign
list, must assign
result to a variable
result to a variable

6.0001 LECTURE 5 21

6.0001 LECTURE 5

25
sorted()
callingcalling sort() mutates the list, returns nothing
does not mutate
calling sorted()
sort() AND
does
list, must sorted()
not mutate
assign
list, must assign
result to a variable
result to a variable

G LISTS
() mutates the list, returns nothing 6.0001 LECTURE 5 21

ed()
6.0001 LECTURE 5

te
n
able 25
side effects still
possible after mutation
LISTS OF LISTS OF LISTS OF...

6.0001 LECTURE 5

26
side effects still
possible
can after mutation
have nested lists

LISTS sideOF LISTS


effects still
possible after mutation
OF LISTS OF...

6.0001 LECTURE 5 22

6.0001 LECTURE 5

26
side effects still
possible
can after mutation
have nested lists

LISTS sideOF LISTS


effects still
possible after mutation
OF LISTS OF...

ISTS OF LISTS OF….


lists
6.0001 LECTURE 5 22

tation 6.0001 LECTURE 5

26
MUTATION AND ITERATION

27
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

27
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)

L1 is [2, 3, 4], not [3, 4]!


◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)

copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)

copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)

copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2

27
◼︎
Moodle quiz ‘Lists 4’

28
HOW TO STORE GROCERY LIST INFO?
GPPython.book Page 262 Monday, March 19, 2018 4:48 PM

items = ['milk', 'eggs', 'bread', 262


'cheese', 'jam']
Lesson 27 Dictio
units = ['cartons', 'count', 'loafs', 'packs', 'jars']
quant = [1, 12, 2, 5, 2]
List Dictionary

0 milk milk 1
A separate list for each item
Each list must have the same length 1 eggs eggs 12

Info stored across lists at same index, 2 bread bread 2

each index refers to info for a different item

You can think of a list as a structure tha


a list can be indexed only by an integer
any object, not just an integer, to any ot
29
ful in situations when you have pairs o
◼︎
◼︎
◼︎
HOW TO UPDATE/RETRIEVE
GROCERY LIST INFO?
def get_quantity(item, item_list, quant_list, unit_list):
i = item_list.index(item)
return (quant_list[i], unit_list[i])

Messy if have a lot of different info to keep track of


Must maintain many lists and pass them as
arguments
Must always index using integers
Must remember to change multiple lists

30
◼︎
◼︎
◼︎
◼︎
DICTIONARY TO THE RESCUE
A BETTER AND CLEANER WAY –
A DICTIONARY
Nice to index item of interest directly (not
always int)
§ nice to index item of interest directly (not always int)
Nice
§ nicetotouse onedata
use one data structure,
structure, no separate
no separate lists lists
A list A dic0onary
0 Elem 1 Key 1 Val 1

1 Elem 2 Key 2 Val 2

2 Elem 3 Key 3 Val 3

3 Elem 4 Key 4 Val 4

… … … …

6.0001 LECTURE 6 43
31
◼︎
◼︎
PYTHON DICTIONARY

Store pairs of data (mappings): 'milk' 1

'eggs' 12
◦ Key
'bread' 2
◦ Value
cheese' 5
Mutable
jam' 2
◦ Can add/delete mappings

my_dict = {} empty dictionary

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}

key1 val1 key2 val2 key3 val3 key4 val4 key5 val5

32
◼︎
◼︎
DICTIONARY LOOKUP

Similar to indexing into a list 'milk' 1

'eggs' 12
Looks up the key
'bread' 2
Returns the value associated
with the key cheese' 5

If key isn’t found, get an error jam' 2

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}


groceries['bread'] ➔ evaluates to 2
groceries['chicken'] ➔ gives a KeyError

33
◼︎
◼︎
◼︎
◼︎
DICTIONARY OPERATIONS

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}

'milk' 1
add an entry
'eggs' 12
groceries['chicken'] = 4
'bread' 2
test if key in dictionary
cheese' 5
'milk' in groceries ➔ evaluates to True
'butter' in groceries ➔ gives a False jam' 2

delete entry
del(groceries['cheese'])

34
◼︎
◼︎
◼︎
Moodle Quiz
‘Dictionary 1’

35
ITERATING OVER DICTIONARY

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}

Iterating over a dictionary will iterate over 'milk' 1


the keys in insertion order 'eggs' 12

'bread' 2
for key in groceries:
print(key, groceries[key]) cheese' 5

milk 1 jam' 2
eggs 12
bread 2
cheese 5
jam 2

36
◼︎
ITERATING OVER DICTIONARY

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}

Get an iterable that acts like a tuple of all 'milk' 1


keys in insertion order 'eggs' 12
groceries.keys()
'bread' 2
for key in groceries.keys():
print(key) cheese' 5

milk jam' 2
eggs
bread
cheese
jam

37
◼︎
ITERATING OVER DICTIONARY

groceries = {'milk':1, 'eggs':12, 'bread':2, 'cheese':5, 'jam':2}

Get an iterable that acts like a tuple of 'milk' 1


all values in insertion order 'eggs' 12
groceries.values()
'bread' 2
for val in groceries.values():
cheese' 5
print(val)
jam' 2
1
12
2
5
2

38
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk']
for k in groceries:
if k in L:
del(groceries[k]

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk']
for k in groceries:
if k in L:
del(groceries[k]

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk'] L = ['bread', 'milk']


for k in groceries: for k in list(groceries):
if k in L: if k in L:
del(groceries[k] del(groceries[k]

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk'] L = ['bread', 'milk']


for k in groceries: for k in list(groceries):
if k in L: if k in L:
del(groceries[k] del(groceries[k]

list of
keys in groceries:
new object

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk'] L = ['bread', 'milk']


for k in groceries: for k in list(groceries):
if k in L: if k in L:
del(groceries[k] del(groceries[k]

list of
keys in groceries:
new object

39
◼︎
◼︎
ITERATING OVER DICTIONARY

Iterating over dictionary while adding or deleting


entries in the dictionary is unsafe
May raise a RuntimeError or miss entries

L = ['bread', 'milk'] L = ['bread', 'milk']


for k in groceries: for k in list(groceries):
if k in L: if k in L:
del(groceries[k] del(groceries[k]

list of
keys in groceries:
new object

39
◼︎
◼︎
Moodle Quiz
‘Dictionary 2’

40
DICTIONARY KEYS AND VALUES

Values:
◦ Any type (immutable and mutable)
◦ Can be duplicates
◦ Can be lists or even other dictionaries!
Keys:
◦ Must be unique
◦ Immutable type (int, float, string, tuple, bool)
✦ Actually, hashable, but must not be mutated if used as a key
✦ All immutable types are hashable
◦ Careful with floats as keys

No order to keys or values


{4: {1: 0}, (1, 3): 'twelve', 'const': [3.14, 2.7, 8.44]}
41
◼︎
◼︎
◼︎
LISTS VS DICTIONARIES

Ordered sequence of Matches “keys” to


elements “values”
Look up elements by Look up one item by
an integer index another item
Indices have an order No order is
guaranteed
Index is an integer
Key can be any
immutable type

42
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
Moodle Quiz
‘Dictionary 3’

43
EXAMPLE: ANALYSE SONG LYRICS

Given song lyrics as a list of words


she_loves_you = ['she', 'loves', 'you', 'yeah',
'yeah', ... ]
Produce a distribution of word frequencies for all words
occurring "at least X times"
◦ X is a parameter
Three functions:
◦ lyrics_to_frequencies(): produce frequency dictionary
◦ most_common_words(): output list of most common words in
dictionary
◦ words_often(): output a list of tuples
(list of words, frequency) ordered by frequency

44
◼︎
◼︎
◼︎
CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict

45
CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list

if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict

45
CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list

if word in myDict: Test if key is in dictionary

myDict[word] += 1
else:
myDict[word] = 1
return myDict

45
CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list

if word in myDict: Test if key is in dictionary

myDict[word] += 1 Update value associated


with a key (mutate a value)
else:
myDict[word] = 1
return myDict

45
CREATING A DICTIONARY

def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list

if word in myDict: Test if key is in dictionary

myDict[word] += 1 Update value associated


with a key (mutate a value)
else:
myDict[word] = 1 Add a new mapping to
dictionary (mutate
return myDict dictionary)

45
USING A DICTIONARY

def most_common_words(freqs):
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)

46
USING A DICTIONARY

def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)

46
USING A DICTIONARY

def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
Can apply max() to an iterable
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)

46
USING A DICTIONARY

def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
Can apply max() to an iterable
words = []
for k in freqs: Iterate over keys in dictionary

if freqs[k] == best:
words.append(k)
return (words, best)

46
EXPLOITING DICTIONARY
PROPERTIES
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w])
else:
done = True
return result

47
EXPLOITING DICTIONARY
PROPERTIES
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w]) mutate dictionary to remove
else: the words that have been
processed
done = True
return result

47

You might also like