0% found this document useful (0 votes)
67 views

Lecture 15 - Tuples and Dictionaries - 2022

This document discusses tuples and dictionaries in Python. Tuples use parentheses and are immutable sequences of elements that can be accessed by index. Dictionaries use curly brackets and consist of key-value pairs where keys must be unique and immutable. The document covers creating, accessing, modifying, and comparing tuples and dictionaries as well as built-in functions like sum(), len(), max(), and dict.unpacking. It contrasts tuples and lists, which are both sequences but lists are mutable, and discusses using tuples as dictionary keys since they are immutable.

Uploaded by

Hải Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Lecture 15 - Tuples and Dictionaries - 2022

This document discusses tuples and dictionaries in Python. Tuples use parentheses and are immutable sequences of elements that can be accessed by index. Dictionaries use curly brackets and consist of key-value pairs where keys must be unique and immutable. The document covers creating, accessing, modifying, and comparing tuples and dictionaries as well as built-in functions like sum(), len(), max(), and dict.unpacking. It contrasts tuples and lists, which are both sequences but lists are mutable, and discusses using tuples as dictionary keys since they are immutable.

Uploaded by

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

Lecture 15 – Tuples and

Dictionaries
Tuples, keys and values for dictionaries
Kok-Seng Wong | 2022
MOTIVATION EXAMPLE 1

[source]
2
MOTIVATION EXAMPLE 2

[source]

3
LEARNING OUTCOMES
Upon the completion of this lecture, students will be able to:
• understand the important characteristics of tuples and
dictionaries in Python.
• define tuples and dictionaries in Python program.

4
TUPLES

5
CREATING A TUPLE
• Tuple: placing all elements inside parentheses separated by
commas enclose tuples in
parentheses
my_tuple = ("a", "e", "i", "o", "u")

• Tuple with empty element:

• Tuple with a singe element:

Must include a
comma at the end!

6
TUPLE UNPACKING
• Tuple unpacking: extract tuple elements into a single variable

7
CLASS PRACTICE
Sample Code:
>>> enemy_list = ("Wray", "Thomas", "Billy")
>>> (e1, e2, e3, e4) = enemy_list

Output:

ValueError: not enough values to unpack (expected 4, got


3)

8
CLASS PRACTICE
Sample Code:
eat(*foods)

use * operator to unpack the tuple so that all


elements can be passed as different parameters

Output:

9
CLASS PRACTICE
Sample Code:

Output:

10
CLASS PRACTICE
Sample Code:
eat_total(*st)

With * operator, eat_total packs all


the arguments into one single variable

Output:

11
TUPLE ARE IMMUTABLE
• tuples are immutable: elements of a tuple cannot be changed once
they have been assigned.

12
OPERATION ON TUPLE: CONCATENATE
• We can concatenate two or more tuples:

13
OPERATION ON TUPLE: DELETE
• We can delete the entire tuple:

14
OPERATION ON TUPLE: SLICING
• We can access a range of items in a tuple by using the slicing
operator:

15
ACCESSING LISTS IN TUPLE

16
REPLACING A TUPLE
• tuples are immutable: but we can replace it with a different tuple.

single element

17
CHANGING A TUPLE
• Tuples are immutable, but the mutable elements can be changed.
• If a value within a tuple is mutable (e.g., a list), then you can change
it:

18
TUPLE() CONVERSION
• We can convert a sequence (list or string) into a tuple:

19
TUPLE ASSIGNMENT
• Conventional method to the values of two variables:

• with tuple assignment:

20
SUM() FUNCTION
• sum(): returns the sum of all items in an iterable

21
OTHER BUILT-IN FUNCTIONS

22
CLASS PRACTICE
Sample Code:
student = ("Jack", "Ali", "Baba", "James", "Thomas")
score = (43, 98, 23, 55, 41)
print(f"Total {len(student)} students in the student tuple")
print(f"The largest item is {max(student)}")
print(f"The largest score is {max(score)}")

Output:

23
COMPARING TUPLES
• Sequences of the same type also support comparisons.
• In particular, tuples (and lists) are compared lexicographically
by comparing corresponding elements.
• To compare equal, every element must compare equal, and the
two sequences must be of the same type and length.

Read More:
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
24
COMPARING TUPLES: EXAMPLE 1

25
COMPARING TUPLES: EXAMPLE 2

26
LISTS VS TUPLES: SIMILARITIES
• Lists and tuples are two of the most commonly used data
structures in Python (with dictionary being the third).
• They are both sequence data types that store a collection of
items/elements.
• They can store items of any data type.
• Any item in the list or tuple is accessible via its index.

27
LISTS VS TUPLES: DIFFERENCES
• Syntax difference: list -> [], tuple -> ()
• Lists are mutable while tuples are immutable (“write-
protect”).
• Cannot use list as a key in a dictionary, but tuple can be
used as dictionary keys.
• Tuple is stored in a single block of memory while list is
stored in two blocks of memory.

28
HOMEWORK

Write a program to find all the common divisors of and and


then the sum of all the divisors. Store the common divisors
using a tuple and then a for-statement to iterate over the
tuple’s elements.

29
DICTIONARIES

30
PYTHON DICTIONARY
• Python Dictionary: a set of key/value pairs.
• Objects in a dictionary can be values of any immutable type.
• Elements are unordered and cannot be accessed with an index.

Colon: to separate a key


from its value
key

my_dictionary = {"A":90, "B":80, "C":70, "F":40}

value
enclose keys and values separate items with a
with a curly brackets comma (,)

31
KEYS AND VALUES

32
EXTRACTING VALUES FROM DICTIONARY
• Dictionary values are accessed by key

>>> my_dictionary = {"A":90, "B":80, "C":70, "F":40}


>>> "A" in my_dictionary
True
>>> my_dictionary["A"]
90

33
ADDING AND MODIFYING AN ITEM

34
DICTIONARY UPDATE()
<dictionary1>.update(<dictionary2>)

• add element(s) to the dictionary if the key is not in the dictionary.


• If the key exists, it updates the key with a new value.

35
UPDATE()

36
DICTIONARY AND FOR-LOOP

Length: the
number of items

Not ordered!

37
SORTING BY KEYS

Ordered by
keys!

38
ITEMS() FUNCTION
• item(): to get a list of tuples with key-pair values

[source]

39
CONVERT LISTS INTO KEY:VALUE PAIR
Sample Code:
my_keys = ["Staff ID", "Staff Name", "Department", "Office"]
my_values = ["100955885", "Ali Baba", "Finance", "Room 1002"]

?
Output:
dictionary : {'Staff ID': '100955885', 'Staff Name': 'Ali Baba', 'Department': 'Finance', 'Office': 'Room 1002'}

40
CLASS PRACTICE
Sample Code:

Output:

41
DICTIONARY UNPACKING: EXAMPLE 1

Unpack operator
(**)

42
DICTIONARY UNPACKING: EXAMPLE 2

43

You might also like