Sets and Dictionaries in Python L5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

SETS AND

DICTIONARIES
IN PYTHON
Mr. Michael Angelo I. Dungo
Instructor I
SETS
• Sets are unordered collections of unique elements. A set is not a sequence type in
Python.
• Elements cannot be accessed by index;
• A set is a mutable object and that means it can be modified.
• A set uses curly braces and commas to separate its elements.
• s1 = {1, 4.5, 'abc'}
• You cannot access items in a set by index because there is no order.
• s1[0]
• Traceback (most recent call last):
• File "<pyshell#33>", line 1, in <module>
• s1[0]
• TypeError: 'set' object does not support indexing
• You cannot access items in a set by index because there is no order.
• There is no concept of the first element of the set. The second element, the third element and
so on.
• In real world, there are many collections that are unordered without duplicates.
• Social Security numbers, email addresses, IP addresses and so on.
• All of these are collections of unique and unordered elements.
• Duplicates are not allowed if we want to have such collections in our applications.
How to check whether a certain element is in the Set?
SET METHODS

• add() -> Adds an element to the set


SET METHODS

• clear() -> Removes all the elements from the set


SET METHODS

• copy() -> Returns a copy of the set


!! the assignment operator (=) creates a reference to the same set object
SET METHODS
• discard() and remove() - remove the specified element from the set
DICTIONARY

● In Python a dictionary is an unordered collection of key: value pairs, separated by commas


and enclosed by curly braces;
● A dictionary is mutable object meaning that we can add or remove elements from the
dictionary.
● The basic structure of a dictionary: key and value pairs
● Values can be any Python object, but keys need to be hashable or immutable objects and
unique.
DICTIONARY
DICTIONARY
DICTIONARY OPERATIONS AND
METHODS
● Membership operation: in and not in
person = {'name': 'John', 'age': 30, 'grades':[7, 9, 10]}
'name' in person
True
● Dictionary Views:
○ dict.keys() -> returns keys only
○ dict.values() -> returns values only
○ dict.items() -> returns (key, value) pairs
● Iteration
for k in person.keys():
print(f'key is {k}')
for k, v in person.items():
print(f'key:{k} , value:{v}')
key:name , value:John key:age , value:30
key:grades , value:[7, 9, 10]
.keys()
.values()
.keys()

You might also like