0% found this document useful (0 votes)
3 views46 pages

Topic 10

This document covers data collection in Python, focusing on tuples, sets, and dictionaries. It explains the characteristics, creation, and usage of each data type, highlighting their differences, methods, and practical applications. The document also includes examples and operations that can be performed with these data structures.

Uploaded by

kielderjohn524
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)
3 views46 pages

Topic 10

This document covers data collection in Python, focusing on tuples, sets, and dictionaries. It explains the characteristics, creation, and usage of each data type, highlighting their differences, methods, and practical applications. The document also includes examples and operations that can be performed with these data structures.

Uploaded by

kielderjohn524
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/ 46

Topic 10 – Data Collection (Tuples, Set

and Dictionary)

Python Programming
CT108-3-1-PYP
TOPIC LEARNING OUTCOMES

At the end of this topic, you should be able to:


– Use tuples as immutable lists
– Use sets for storing and fast accessing non-duplicate elements
– Understand the performance differences between sets and lists
– Understand how to store key/value pairs in a dictionary and access
value using the key
– Use dictionaries to develop applications (§14.6).

Python Programming Tuple, Set and Dictionary SLIDE 2


CT108-3-1-PYP
Contents & Structure

Tuple
Create Adding an element Accessing

Set
Create Accessing

Dictionary

Create Accessing Adding an element


Python Programming Tuple, Set and Dictionary SLIDE 3
CT108-3-1-PYP ‹#›
Tuple

• Tuples are like lists except they are immutable like strings.
• Once created, elements cannot be changed.
• If the elements of a list in the application do not change, use a tuple
to prevent data from being modified accidentally.
• Tuples are more efficient than lists.
• IMPORTANT! tuples can be accessed like lists. However, tuples are
NOT list.
• Collection of objects which is ordered and unchangeable
• In Python tuples are written with round brackets (parentheses), rather
than square brackets
• The parentheses are optional but is a good practice to write it.
Python Programming Tuple, Set and Dictionary SLIDE 4
CT108-3-1-PYP
Tuples are “immutable”

• Unlike a list, once you create a tuple, you cannot alter its contents - like
a string

x = [9, 8, 7] y = 'ABC' z = (5, 4, 3)


x[2] = 6 y[2] = 'D' z[2] = 0
print(x) print(y) print(z)
TypeError: 'str' TypeError:
object does not 'tuple' object
support item does not
assignment support item
assignment

Python Programming Tuple, Set and Dictionary SLIDE 5


CT108-3-1-PYP
Things NOT to do With Tuples

x = (3, 2, 1)
x.sort()
print(x)
AttributeError: 'tuple' object has no attribute 'sort’
x.reverse()
AttributeError: 'tuple' object has no attribute 'reverse’
x.append(5)
AttributeError: 'tuple' object has no attribute 'append

Python Programming Tuple, Set and Dictionary SLIDE 6


CT108-3-1-PYP
A Tale of Two

l = list()
print(dir(l))
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort’]

t = tuple()
print(dir(t))
['count', 'index']

Python Programming Tuple, Set and Dictionary SLIDE 7


CT108-3-1-PYP
Tuple – More Efficient

Since Python does not have to build tuple structures to be


modifiable, they are simpler and more efficient in terms of memory
use and performance than lists

So in our program when we are making “temporary variables” we


prefer tuples over lists

Python Programming Tuple, Set and Dictionary SLIDE 8


CT108-3-1-PYP
Creating Tuple

tuple = ()
Empty tuple
print(tuple)

tuple = (1, 2, 3)
Tuple with elements
print(tuple)

tuple = (1, "Tuple", 3.7)


Tuple with different datatypes
print(tuple)

tuple = ("cat", [100, 98, 65], (1, 2, 3))


Nested tuple
print(tuple)

Python Programming Tuple, Set and Dictionary SLIDE 9


CT108-3-1-PYP
Accessing Tuple

• Using Indexing (forward or backward)


fruits = (“Cherry”, “Guava”, “Mango”)
print(fruits[2]) Mango
print(fruits[-2]) Guava

• Slicing
fruits = (“Cherry”, “Guava”, “Mango”)
print(fruits[1:3]) (Guava, Mango)
print(fruits[:-1]) (Cherry, Guava)
print(fruits[2:]) (Mango)
print(fruits[:])
(Cherry, Guava, Mango)

Python Programming Tuple, Set and Dictionary SLIDE 10


CT108-3-1-PYP
Accessing Tuple with For loops

fruits = ("Cherry", "Guava", "Mango")


for i in fruits:
print(i)

Python Programming Tuple, Set and Dictionary SLIDE 11


CT108-3-1-PYP
Using len() in Tuple

fruits = ("Cherry", "Guava", "Mango")


print(len(fruits))

Python Programming Tuple, Set and Dictionary SLIDE 12


CT108-3-1-PYP
>>>
Removing Tuples
Tuple vs. Lists

• You cannot remove or delete or update items in a tuple.

• Tuples are unchangeable, so you cannot remove items from it, but
you can delete the tuple completely

Python Programming Tuple, Set and Dictionary SLIDE 13


CT108-3-1-PYP
TUPLE METHODS

• Python provides two built-in methods that you can use on tuples.

1. count() Method

2. index() Method

Python Programming Tuple, Set and Dictionary SLIDE 14


CT108-3-1-PYP
TUPLE METHODS – index()

• Return the index of element

fruits = ("Cherry", "Guava", "Mango")


print(fruits.index('Cherry')) index() method
returns index
value of
‘Cherry’ present
in the given
tuple

Python Programming Tuple, Set and Dictionary SLIDE 15


CT108-3-1-PYP
TUPLE METHODS – count()

• Return the number of times the value appears in the tuple

fruits = ("Cherry", "Guava", "Mango")


print(fruits.count('Cherry')) count() method
returns total
number of
times ‘Cherry’
present in the
given tuple

Python Programming Tuple, Set and Dictionary SLIDE 16


CT108-3-1-PYP
Tuple is Comparable

• The comparison operators work with tuples and other sequences.


• If the first item is equal, Python goes on to the next element, and so
on, until it finds elements that differ.
x = (0, 1, 2) < (5, 1, 2)
print(x)

y = (0, 1, 2000000) == (0, 3, 4)


print(y)

z = ( 'Jones', 'Sally' ) <= ('Jones', 'Sam')


print(z)

a = ( 'Jones', 'Sally') == ('Adams', 'Sam')


print(a)

Python Programming Tuple, Set and Dictionary SLIDE 17


CT108-3-1-PYP
Overview – Set and Dictionary

• Python doesn’t have traditional vectors and arrays!


• Instead, Python makes heavy use of the dictionary datatype (a
hashtable) which can serve as a sparse array
• Efficient traditional arrays are available as modules that interface to C
• A Python set is derived from a dictionary.

Python Programming Tuple, Set and Dictionary SLIDE 18


CT108-3-1-PYP
SET

Python Programming Tuple, Set and Dictionary SLIDE 19


CT108-3-1-PYP
Introduction

A set is a mutable collection of unique unordered immutable objects.

The set can change.

The elements of the set can not change,

The element can be removed or inserted.

Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

Python Programming Tuple, Set and Dictionary SLIDE 20


CT108-3-1-PYP
Creating a Set
• A set is created by placing all the elements inside curly braces {},
separated by comma or by using the built-in function set().
• The elements can be of different types (integer, float, tuple, string
etc.).
• But a set cannot have a mutable element, like list or dictionary, as its
element
• Empty Set
emptySet = { } #this will return a dictionary
print(emptySet)
• Empty Set
emptySet = set()#this will return set
print(emptySet)
• Set with elements
Python Programming
set1 = {1, 2, 3, 4, 3, 2} Tuple, Set and Dictionary SLIDE 21
CT108-3-1-PYP
Set - Elements

• A set can contain elements of different type


mySet = {1.0, "Hello", (1, 2, 3)}
print(mySet)
• A set cannot contain list
mySet = {[1, 2, 3]}
print(mySet)
TypeError: unhashable type: 'list'
• But can convert a list to set using set function
mySet = set([1, 2, 3])
print(mySet)

Python Programming Tuple, Set and Dictionary SLIDE 22


CT108-3-1-PYP
Set - Method

Size of the set – how many elements in


the set. len(fruits)

Adding one element to a set. fruits.add(’kiwi’)


Adding several elements (as list) to a
set, performance for long list. fruits.update([’strawberry’, ’elderberry’])
Removing element, KeyError if not
present. fruits.remove(’kiwi’)
Removing element, no error if not
present. fruits.discard(’kiwi’)

Making a shallow copy. f = fruits.copy()

Clearing a set. Keeps the list identity. fruits.clear()

Python Programming Tuple, Set and Dictionary SLIDE 23


CT108-3-1-PYP
Sample - Set

• Read a string and find the number of unique characters in it:


string = "My Python Programming"
unique = set(string)

print("Length of strings = ", len(unique))


print("List of unique character = ", unique)

string = list(string)
for element in unique:
string.remove(element)

print("Repeated Characters: ", set(string))

Python Programming Tuple, Set and Dictionary SLIDE 24


CT108-3-1-PYP
Set - Operations

• Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference.
• It can be done with operators or methods
Method Operator Description

union | Contains all elements that are


in set A or in set B
intersection & Contains all elements that are
in both sets A and B
difference - Contains all elements that are
in A but not in B
symmetric_differenc ^ Contains all elements that are
e either
• in set A but not in set B or
• in set B but not in set A
Python Programming Tuple, Set and Dictionary SLIDE 25
CT108-3-1-PYP
Set – Operations (Sample)

setA = {1,2,3,4,5}
setB = {3,4,5,6,7}

print("Union: ", setA|setB)


print("Intersection: ", setA & setB)
print("Difference: ", setA - setB)
print("Symmetric Difference: ", setA ^ setB)

Python Programming Tuple, Set and Dictionary SLIDE 26


CT108-3-1-PYP
Summary of Set

• Set do not contain duplicate


• Set is immutable
• Set have no order
• Set do not support indexing

Python Programming Tuple, Set and Dictionary SLIDE 27


CT108-3-1-PYP
DICTIONARIES

Python Programming Tuple, Set and Dictionary SLIDE 28


CT108-3-1-PYP
Introduction - Dictionaries

List Dictionaries
A linear collection of values that stay in A “bag” of values, each with its own
order. label

Python Programming Tuple, Set and Dictionary SLIDE 29


CT108-3-1-PYP
Dictionaries

Dictionaries are Python’s most powerful data collection

Dictionaries allow us to do fast database-like operations in Python

Dictionaries have different names in different languages


Properties or Map or HashMap -
Associative Arrays - Perl / PHP Property Bag - C# / .Net
Java

Python Programming Tuple, Set and Dictionary SLIDE 30


CT108-3-1-PYP
Dictionaries

Store pairs of entries called items


{ 'CS' : '743-713-3350', 'UHPD' : '713-743-3333'}

A key
Each pair of entries contains
A value

Key and values are separated by a colon

Pairs of entries are separated by commas

Dictionary is enclosed within curly braces

Python Programming Tuple, Set and Dictionary SLIDE 31


CT108-3-1-PYP
Dicitonaries

• A={1:"one",2:"two",3:"three"}

1 one
A= 2 two
3 three

KEY VALUES
Python Programming
S
Tuple, Set and Dictionary SLIDE 32
CT108-3-1-PYP
Creating a Dictionaries

Creating a dictionary is as simple as placing items inside curly braces


{} separated by comma.

Each element in a dictionary is represented by a key: value pair.

While values can be of any data


type and can repeat, keys must be marks = {“python”: 87, “OS”: 80, “DB”:
of immutable type and must be 70}
unique

Python Programming Tuple, Set and Dictionary SLIDE 33


CT108-3-1-PYP
Accessing elements in the Dictionaries

• While indexing is used with other container types to access values,


dictionary uses keys.
• Key can be used either inside square brackets or with the get()
method.
• The difference while using get() is that it returns None instead of
KeyError, if the key is not found
Return KeyError
print(marks["python"])
print(marks["java"])
print(marks.get("DB")) Return None
print(marks.get("java"))

Python Programming Tuple, Set and Dictionary SLIDE 34


CT108-3-1-PYP
Adding elements into dictionaries

Dictionary are mutable.

Can add new items or change the value of existing items using assignment
operator.

student = {"name": "Paola", "module": "Python"}

If the key is already present, value print(student)


student["course"] = "ICT(SE)"
gets updated, else a new key: value print(student)
pair is added to the dictionary student["module"] = "Database"
print(student)

Python Programming Tuple, Set and Dictionary SLIDE 35


CT108-3-1-PYP
Deleting elements from dictionaries

Can remove a particular item in a dictionary by using the method pop().

This method removes as item with the provided key and returns the value.

All the items can be removed at once using the clear() method.

student = {"name": "Paola", "module": "Python"}


Can also use the del keyword to student.pop("name") or del student["name"]
remove individual items or the entire print(student)
student.clear()
dictionary itself print(student)

Python Programming Tuple, Set and Dictionary SLIDE 36


CT108-3-1-PYP
Delete Random Elements

The method, popitem() can be used to remove and return an


arbitrary item (key, value) form the dictionary.

student = {"name": "Paola", "module":


Raises KeyError if the "Python"}

dictionary is empty student.popitem()


print(student)

Python Programming Tuple, Set and Dictionary SLIDE 37


CT108-3-1-PYP
Iterating through the dictionaries

• Use for loop to iterating through each of keys and values in the
dictionaries:
marks = {"python": 87, "OS": 80, "DB": 70}

for subject in marks:


print(subject)

for subject in marks:


score = marks[subject]
print(subject, score)
• Or using items()

Python Programming Tuple, Set and Dictionary SLIDE 38


CT108-3-1-PYP
Checking the Frequency of elements

text = "Python Dictionary is Awesome"

freq = {}
for ch in text:
freq[ch] = freq.get(ch,0) + 1

for key in freq:


print(key, freq[key])

Python Programming Tuple, Set and Dictionary SLIDE 39


CT108-3-1-PYP
Dictionaries: Built-in Method

Dictionary Method Meaning


clear() Remove all items form the dictionary
copy() Returns (shallow) copy of dictionary.
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults
to None)
items() Return a new view of the dictionary's items (key, value)
keys() Return a new view of the dictionary's keys
update() Update the dictionary with the key/value pairs from other,
overwriting existing keys
values() Return a new view of the dictionary's value
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to
v(defaults to None)
pop(key[,d]) Remove the item with key and return its value or d if key is not
found. If d is not provided and key is not found, raises KeyError
popitem() Remove and return an arbitrary item (key, value). Raises
KeyError if the dictionary is empty
Python Programming Tuple, Set and Dictionary SLIDE 40
CT108-3-1-PYP
Dictionaries: Built-in Function

Function Description
len() Return the length (the number of items) in the
dictionary
marks = {"python": 87, "OS": 80, "DB": 70}
print(len(marks))
sorted() Return a new sorted list of keys in the dictionary
print(sorted(marks))

Python Programming Tuple, Set and Dictionary SLIDE 41


CT108-3-1-PYP
Dictionary in Dictionaries

• Dictionaries can contain key: value pairs where the values are again
are dictionaries
Malaysia = {"Johor": {"capital": "Johor Bahru"},
"Kedah":{"capital": "Alor Setar"}}

print("Capital of Johor: ", Malaysia["Johor"]["capital"])

Python Programming Tuple, Set and Dictionary SLIDE 42


CT108-3-1-PYP
Summary / Recap of Main Points

• Creating an empty list or new list


• Adding an element to list
• Listing the element of a list
• List processing
• Methods used with lists

Python Programming Tuple, Set and Dictionary SLIDE 43


CT108-3-1-PYP
Contents & Structure

Tuple
Create Adding an element Accessing

Set
Create Accessing

Dictionary

Create Accessing Adding an element


Python Programming Tuple, Set and Dictionary SLIDE 44 ‹#›
CT108-3-1-PYP
What To Expect Next Week

In Class Preparation for Class


• File Handling • Read about file handling with
Python

Python Programming Tuple, Set and Dictionary SLIDE 45


CT108-3-1-PYP
Python Programming Tuple, Set and Dictionary SLIDE 46
CT108-3-1-PYP

You might also like