SlideShare a Scribd company logo
Tuples and dictionaries
Module 3 Functions, Tuples, Dictionaries,
Data processing
Module 3 Tuples and dictionaries
Sequence types & mutability
sequence types
• is a type of data
• is data which can be scanned by the for loop
2 kinds of Python data
• Mutable data can be freely updated at any time
• Immutable data cannot be modified in this way
Module 3 Tuples and dictionaries
What is a tuple?
tuple_1 = (1, 2, 4, 8)
tuple_2 = 1., .5, .25, .125
print(tuple_1)
print(tuple_2)
(1, 2, 4, 8)
(1.0, 0.5, 0.25, 0.125)
create a tuple
empty_tuple = () one_element_tuple_1 = (1, )
Module 3 Tuples and dictionaries
Do not modify tuple's contents!
my_tuple = (1, 10, 100,
1000)
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[1:])
print(my_tuple[:-2])
for elem in my_tuple:
print(elem)
1
1000
(10, 100, 1000)
(1, 10)
1
10
100
1000
my_tuple = (1, 10, 100,
1000)
my_tuple.append(10000)
del my_tuple[0]
my_tuple[1] = -10
print(my_tuple)
AttributeError: 'tuple' object has no attribute 'append'
Module 3 Tuples and dictionaries
How to use a tuple
my_tuple = (1, 10, 100)
t1 = my_tuple + (1000,
10000)
t2 = my_tuple * 3
print(len(t2))
print(t1)
print(t2)
print(10 in my_tuple)
print(-10 not in my_tuple)
9
(1, 10, 100, 1000, 10000)
(1, 10, 100, 1, 10, 100, 1, 10, 100)
True
True
var = 123
t1 = (1, )
t2 = (2, )
t3 = (3, var)
t1, t2, t3 = t2, t3, t1
print(t1, t2, t3)
(2,) (3, 123) (1,)
Module 3 Tuples and dictionaries
What is a dictionary?
each key must be unique
a key may be any immutable type of object
a dictionary holds pairs of values
the len() function works for dictionaries
a dictionary is a one-way tool
Module 3 Tuples and dictionaries
How to make a dictionary?
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310}
empty_dictionary = {}
print(dictionary['cat'])
print(phone_numbers['Suzy'])
chat
22657854310
dictionary = {
"cat": "chat",
"dog": "chien",
"horse": "cheval"
}
words = ['cat', 'lion', 'horse']
for word in words:
if word in dictionary:
print(word, "->", dictionary[word])
else:
print(word, "is not in dictionary")
cat -> chat
lion is not in dictionary
horse -> cheval
Module 3 Tuples and dictionaries
keys(), sorted()
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for key in dictionary.keys():
print(key, "->", dictionary[key])
horse -> cheval
dog -> chien
cat -> chat
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for key in sorted(dictionary.keys()):
print(key, "->", dictionary[key])
cat -> chat
dog -> chien
horse -> cheval
Module 3 Tuples and dictionaries
items() & values() methods
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for english, french in dictionary.items():
print(english, "->", french)
cat -> chat
dog -> chien
horse -> cheval
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for french in dictionary.values():
print(french)
cheval
chien
chat
Module 3 Tuples and dictionaries
Modifying and adding values
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['cat'] = 'minou'
print(dictionary)
{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['swan'] = 'cygne'
print(dictionary)
{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': 'cygne'}
Module 3 Tuples and dictionaries
Tuples and dictionaries
• you need a program to evaluate the
students' average scores;
• the program should ask for the student's
name, followed by her/his single score;
• the names may be entered in any order;
• entering an empty name finishes the
inputting of the data;
• a list of all names, together with the
evaluated average score, should be then
emitted.
school_class = {}
while True:
name = input("Enter the student's name: ")
if name == '':
break
score = int(input("Enter the student's score (0-10): "))
if score not in range(0, 11):
break
if name in school_class:
school_class[name] += (score,)
else:
school_class[name] = (score,)
for name in sorted(school_class.keys()):
adding = 0
counter = 0
for score in school_class[name]:
adding += score
counter += 1
print(name, ":", adding / counter)
Module 3 Tuples and dictionaries
Key takeaways: tuples
Tuples are ordered and unchangeable (immutable) collections of data.
You can create an empty tuple, one-element tuple.
You can access tuple elements by indexing them.
Tuples are immutable, which means you cannot change their elements
You can loop through a tuple elements .
Module 3 Tuples and dictionaries
EXTRA: tuple(), list()
my_tuple = tuple((1, 2, "string"))
print(my_tuple)
my_list = [2, 4, 6]
print(my_list) # outputs: [2, 4, 6]
print(type(my_list)) # outputs: <class 'list'>
tup = tuple(my_list)
print(tup) # outputs: (2, 4, 6)
print(type(tup)) # outputs: <class 'tuple'>
tup = 1, 2, 3,
my_list = list(tup)
print(type(my_list)) # outputs: <class 'list'>
Module 3 Tuples and dictionaries
Key takeaways: dictionaries 1
Dictionaries are unordered*, changeable (mutable), and indexed
collections of data.
If you want to access a dictionary item:
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
item_1 = pol_eng_dictionary["gleba"] # ex. 1
print(item_1) # outputs: soil
item_2 = pol_eng_dictionary.get("woda")
print(item_2) # outputs: water
Module 3 Tuples and dictionaries
Key takeaways: dictionaries 2
If you want to change the value associated with a specific key:
To add or remove a key (and the associated value):
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
pol_eng_dictionary["zamek"] = "lock"
item = pol_eng_dictionary["zamek"]
print(item) # outputs: lock
phonebook = {} # an empty dictionary
phonebook["Adam"] = 3456783958 # create/add a key-value pair
print(phonebook) # outputs: {'Adam': 3456783958}
del phonebook["Adam"]
print(phonebook) # outputs: {}
Module 3 Tuples and dictionaries
Key takeaways: dictionaries 3
You can use the for loop to loop through a dictionary:
pol_eng_dictionary = {"kwiat": "flower"}
pol_eng_dictionary.update({"gleba": "soil"})
print(pol_eng_dictionary) # outputs: {'kwiat': 'flower', 'gleba': 'soil'}
pol_eng_dictionary.popitem()
print(pol_eng_dictionary) # outputs: {'kwiat': 'flower'}
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
for item in pol_eng_dictionary:
print(item)
# outputs: zamek
# woda
# gleba
Module 3 Tuples and dictionaries
Key takeaways: dictionaries 4
If you want to loop through a dictionary's keys and values:
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
for key, value in pol_eng_dictionary.items():
print("Pol/Eng ->", key, ":", value)
To check if a given key exists in a dictionary:
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
if "zamek" in pol_eng_dictionary:
print("Yes")
else:
print("No")
Module 3 Tuples and dictionaries
Key takeaways: dictionaries 5
To remove a specific item:
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
print(len(pol_eng_dictionary)) # outputs: 3
del pol_eng_dictionary["zamek"] # remove an item
print(len(pol_eng_dictionary)) # outputs: 2
pol_eng_dictionary.clear() # removes all the items
print(len(pol_eng_dictionary)) # outputs: 0
del pol_eng_dictionary # removes the dictionary
To copy a dictionary:
pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"}
copy_dictionary = pol_eng_dictionary.copy()
Module 3 Tuples and dictionaries
LAB Practice
29. Tic-Tac-Toe
Congratulations!
You have completed Module 3
the defining and
using of functions
the concept of
passing
arguments in
different ways
name scope
issues
tuples and
dictionaries
Ad

More Related Content

What's hot (18)

Sets in python
Sets in pythonSets in python
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
Shahriar Robbani
 
Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014
Puppet
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
Colin Su
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
Introduction to Search Systems - ScaleConf Colombia 2017
Introduction to Search Systems - ScaleConf Colombia 2017Introduction to Search Systems - ScaleConf Colombia 2017
Introduction to Search Systems - ScaleConf Colombia 2017
Toria Gibbs
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
A Search Index is Not a Database Index - Full Stack Toronto 2017
A Search Index is Not a Database Index - Full Stack Toronto 2017A Search Index is Not a Database Index - Full Stack Toronto 2017
A Search Index is Not a Database Index - Full Stack Toronto 2017
Toria Gibbs
 
Slicing in Python - What is It?
Slicing in Python - What is It?Slicing in Python - What is It?
Slicing in Python - What is It?
💾 Radek Fabisiak
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
Software Guru
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Swift tips and tricks
Swift tips and tricksSwift tips and tricks
Swift tips and tricks
HomeroJuniorOliveira1
 
Elixir pattern matching and recursion
Elixir pattern matching and recursionElixir pattern matching and recursion
Elixir pattern matching and recursion
Bob Firestone
 
Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014
Puppet
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
Colin Su
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
Introduction to Search Systems - ScaleConf Colombia 2017
Introduction to Search Systems - ScaleConf Colombia 2017Introduction to Search Systems - ScaleConf Colombia 2017
Introduction to Search Systems - ScaleConf Colombia 2017
Toria Gibbs
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
A Search Index is Not a Database Index - Full Stack Toronto 2017
A Search Index is Not a Database Index - Full Stack Toronto 2017A Search Index is Not a Database Index - Full Stack Toronto 2017
A Search Index is Not a Database Index - Full Stack Toronto 2017
Toria Gibbs
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
Software Guru
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Elixir pattern matching and recursion
Elixir pattern matching and recursionElixir pattern matching and recursion
Elixir pattern matching and recursion
Bob Firestone
 

Similar to Python PCEP Tuples and Dictionaries (20)

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
ESIT135 Problem Solving Using Python Notes of Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-3ESIT135 Problem Solving Using Python Notes of Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
RajKumar Rampelli
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
H K
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
Marc Gouw
 
Dictionary
DictionaryDictionary
Dictionary
Pooja B S
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
ITS-16163: Module 5 Using Lists and Dictionaries
ITS-16163: Module 5 Using Lists and DictionariesITS-16163: Module 5 Using Lists and Dictionaries
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
Lahore Garrison University
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
ESIT135 Problem Solving Using Python Notes of Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-3ESIT135 Problem Solving Using Python Notes of Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
RajKumar Rampelli
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
H K
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
Marc Gouw
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
ITS-16163: Module 5 Using Lists and Dictionaries
ITS-16163: Module 5 Using Lists and DictionariesITS-16163: Module 5 Using Lists and Dictionaries
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
GauravPandey43518
 
Ad

More from IHTMINSTITUTE (19)

Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Creating Simple Functions
Python PCEP Creating Simple FunctionsPython PCEP Creating Simple Functions
Python PCEP Creating Simple Functions
IHTMINSTITUTE
 
Python PCEP Functions And Scopes
Python PCEP Functions And ScopesPython PCEP Functions And Scopes
Python PCEP Functions And Scopes
IHTMINSTITUTE
 
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function Parameters
IHTMINSTITUTE
 
Python PCEP Functions
Python PCEP FunctionsPython PCEP Functions
Python PCEP Functions
IHTMINSTITUTE
 
Python PCEP Multidemensional Arrays
Python PCEP Multidemensional ArraysPython PCEP Multidemensional Arrays
Python PCEP Multidemensional Arrays
IHTMINSTITUTE
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On Lists
IHTMINSTITUTE
 
Python PCEP Sorting Simple Lists
Python PCEP Sorting Simple ListsPython PCEP Sorting Simple Lists
Python PCEP Sorting Simple Lists
IHTMINSTITUTE
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of Data
IHTMINSTITUTE
 
Python PCEP Logic Bit Operations
Python PCEP Logic Bit OperationsPython PCEP Logic Bit Operations
Python PCEP Logic Bit Operations
IHTMINSTITUTE
 
Python PCEP Loops
Python PCEP LoopsPython PCEP Loops
Python PCEP Loops
IHTMINSTITUTE
 
Python PCEP Comparison Operators And Conditional Execution
Python PCEP Comparison Operators And Conditional ExecutionPython PCEP Comparison Operators And Conditional Execution
Python PCEP Comparison Operators And Conditional Execution
IHTMINSTITUTE
 
Python PCEP How To Talk To Computer
Python PCEP How To Talk To ComputerPython PCEP How To Talk To Computer
Python PCEP How To Talk To Computer
IHTMINSTITUTE
 
Python PCEP Variables
Python PCEP VariablesPython PCEP Variables
Python PCEP Variables
IHTMINSTITUTE
 
Python PCEP Operators
Python PCEP OperatorsPython PCEP Operators
Python PCEP Operators
IHTMINSTITUTE
 
Python PCEP Literals
Python PCEP LiteralsPython PCEP Literals
Python PCEP Literals
IHTMINSTITUTE
 
IHTM Python PCEP Hello World
IHTM Python PCEP Hello WorldIHTM Python PCEP Hello World
IHTM Python PCEP Hello World
IHTMINSTITUTE
 
IHTM Python PCEP Introduction to Python
IHTM Python PCEP Introduction to PythonIHTM Python PCEP Introduction to Python
IHTM Python PCEP Introduction to Python
IHTMINSTITUTE
 
Python PCEP Welcome Opening
Python PCEP Welcome OpeningPython PCEP Welcome Opening
Python PCEP Welcome Opening
IHTMINSTITUTE
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Creating Simple Functions
Python PCEP Creating Simple FunctionsPython PCEP Creating Simple Functions
Python PCEP Creating Simple Functions
IHTMINSTITUTE
 
Python PCEP Functions And Scopes
Python PCEP Functions And ScopesPython PCEP Functions And Scopes
Python PCEP Functions And Scopes
IHTMINSTITUTE
 
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function Parameters
IHTMINSTITUTE
 
Python PCEP Functions
Python PCEP FunctionsPython PCEP Functions
Python PCEP Functions
IHTMINSTITUTE
 
Python PCEP Multidemensional Arrays
Python PCEP Multidemensional ArraysPython PCEP Multidemensional Arrays
Python PCEP Multidemensional Arrays
IHTMINSTITUTE
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On Lists
IHTMINSTITUTE
 
Python PCEP Sorting Simple Lists
Python PCEP Sorting Simple ListsPython PCEP Sorting Simple Lists
Python PCEP Sorting Simple Lists
IHTMINSTITUTE
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of Data
IHTMINSTITUTE
 
Python PCEP Logic Bit Operations
Python PCEP Logic Bit OperationsPython PCEP Logic Bit Operations
Python PCEP Logic Bit Operations
IHTMINSTITUTE
 
Python PCEP Comparison Operators And Conditional Execution
Python PCEP Comparison Operators And Conditional ExecutionPython PCEP Comparison Operators And Conditional Execution
Python PCEP Comparison Operators And Conditional Execution
IHTMINSTITUTE
 
Python PCEP How To Talk To Computer
Python PCEP How To Talk To ComputerPython PCEP How To Talk To Computer
Python PCEP How To Talk To Computer
IHTMINSTITUTE
 
Python PCEP Variables
Python PCEP VariablesPython PCEP Variables
Python PCEP Variables
IHTMINSTITUTE
 
Python PCEP Operators
Python PCEP OperatorsPython PCEP Operators
Python PCEP Operators
IHTMINSTITUTE
 
Python PCEP Literals
Python PCEP LiteralsPython PCEP Literals
Python PCEP Literals
IHTMINSTITUTE
 
IHTM Python PCEP Hello World
IHTM Python PCEP Hello WorldIHTM Python PCEP Hello World
IHTM Python PCEP Hello World
IHTMINSTITUTE
 
IHTM Python PCEP Introduction to Python
IHTM Python PCEP Introduction to PythonIHTM Python PCEP Introduction to Python
IHTM Python PCEP Introduction to Python
IHTMINSTITUTE
 
Python PCEP Welcome Opening
Python PCEP Welcome OpeningPython PCEP Welcome Opening
Python PCEP Welcome Opening
IHTMINSTITUTE
 
Ad

Recently uploaded (19)

OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 

Python PCEP Tuples and Dictionaries

  • 1. Tuples and dictionaries Module 3 Functions, Tuples, Dictionaries, Data processing
  • 2. Module 3 Tuples and dictionaries Sequence types & mutability sequence types • is a type of data • is data which can be scanned by the for loop 2 kinds of Python data • Mutable data can be freely updated at any time • Immutable data cannot be modified in this way
  • 3. Module 3 Tuples and dictionaries What is a tuple? tuple_1 = (1, 2, 4, 8) tuple_2 = 1., .5, .25, .125 print(tuple_1) print(tuple_2) (1, 2, 4, 8) (1.0, 0.5, 0.25, 0.125) create a tuple empty_tuple = () one_element_tuple_1 = (1, )
  • 4. Module 3 Tuples and dictionaries Do not modify tuple's contents! my_tuple = (1, 10, 100, 1000) print(my_tuple[0]) print(my_tuple[-1]) print(my_tuple[1:]) print(my_tuple[:-2]) for elem in my_tuple: print(elem) 1 1000 (10, 100, 1000) (1, 10) 1 10 100 1000 my_tuple = (1, 10, 100, 1000) my_tuple.append(10000) del my_tuple[0] my_tuple[1] = -10 print(my_tuple) AttributeError: 'tuple' object has no attribute 'append'
  • 5. Module 3 Tuples and dictionaries How to use a tuple my_tuple = (1, 10, 100) t1 = my_tuple + (1000, 10000) t2 = my_tuple * 3 print(len(t2)) print(t1) print(t2) print(10 in my_tuple) print(-10 not in my_tuple) 9 (1, 10, 100, 1000, 10000) (1, 10, 100, 1, 10, 100, 1, 10, 100) True True var = 123 t1 = (1, ) t2 = (2, ) t3 = (3, var) t1, t2, t3 = t2, t3, t1 print(t1, t2, t3) (2,) (3, 123) (1,)
  • 6. Module 3 Tuples and dictionaries What is a dictionary? each key must be unique a key may be any immutable type of object a dictionary holds pairs of values the len() function works for dictionaries a dictionary is a one-way tool
  • 7. Module 3 Tuples and dictionaries How to make a dictionary? dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310} empty_dictionary = {} print(dictionary['cat']) print(phone_numbers['Suzy']) chat 22657854310 dictionary = { "cat": "chat", "dog": "chien", "horse": "cheval" } words = ['cat', 'lion', 'horse'] for word in words: if word in dictionary: print(word, "->", dictionary[word]) else: print(word, "is not in dictionary") cat -> chat lion is not in dictionary horse -> cheval
  • 8. Module 3 Tuples and dictionaries keys(), sorted() dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for key in dictionary.keys(): print(key, "->", dictionary[key]) horse -> cheval dog -> chien cat -> chat dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for key in sorted(dictionary.keys()): print(key, "->", dictionary[key]) cat -> chat dog -> chien horse -> cheval
  • 9. Module 3 Tuples and dictionaries items() & values() methods dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for english, french in dictionary.items(): print(english, "->", french) cat -> chat dog -> chien horse -> cheval dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for french in dictionary.values(): print(french) cheval chien chat
  • 10. Module 3 Tuples and dictionaries Modifying and adding values dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} dictionary['cat'] = 'minou' print(dictionary) {'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'} dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} dictionary['swan'] = 'cygne' print(dictionary) {'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': 'cygne'}
  • 11. Module 3 Tuples and dictionaries Tuples and dictionaries • you need a program to evaluate the students' average scores; • the program should ask for the student's name, followed by her/his single score; • the names may be entered in any order; • entering an empty name finishes the inputting of the data; • a list of all names, together with the evaluated average score, should be then emitted. school_class = {} while True: name = input("Enter the student's name: ") if name == '': break score = int(input("Enter the student's score (0-10): ")) if score not in range(0, 11): break if name in school_class: school_class[name] += (score,) else: school_class[name] = (score,) for name in sorted(school_class.keys()): adding = 0 counter = 0 for score in school_class[name]: adding += score counter += 1 print(name, ":", adding / counter)
  • 12. Module 3 Tuples and dictionaries Key takeaways: tuples Tuples are ordered and unchangeable (immutable) collections of data. You can create an empty tuple, one-element tuple. You can access tuple elements by indexing them. Tuples are immutable, which means you cannot change their elements You can loop through a tuple elements .
  • 13. Module 3 Tuples and dictionaries EXTRA: tuple(), list() my_tuple = tuple((1, 2, "string")) print(my_tuple) my_list = [2, 4, 6] print(my_list) # outputs: [2, 4, 6] print(type(my_list)) # outputs: <class 'list'> tup = tuple(my_list) print(tup) # outputs: (2, 4, 6) print(type(tup)) # outputs: <class 'tuple'> tup = 1, 2, 3, my_list = list(tup) print(type(my_list)) # outputs: <class 'list'>
  • 14. Module 3 Tuples and dictionaries Key takeaways: dictionaries 1 Dictionaries are unordered*, changeable (mutable), and indexed collections of data. If you want to access a dictionary item: pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} item_1 = pol_eng_dictionary["gleba"] # ex. 1 print(item_1) # outputs: soil item_2 = pol_eng_dictionary.get("woda") print(item_2) # outputs: water
  • 15. Module 3 Tuples and dictionaries Key takeaways: dictionaries 2 If you want to change the value associated with a specific key: To add or remove a key (and the associated value): pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} pol_eng_dictionary["zamek"] = "lock" item = pol_eng_dictionary["zamek"] print(item) # outputs: lock phonebook = {} # an empty dictionary phonebook["Adam"] = 3456783958 # create/add a key-value pair print(phonebook) # outputs: {'Adam': 3456783958} del phonebook["Adam"] print(phonebook) # outputs: {}
  • 16. Module 3 Tuples and dictionaries Key takeaways: dictionaries 3 You can use the for loop to loop through a dictionary: pol_eng_dictionary = {"kwiat": "flower"} pol_eng_dictionary.update({"gleba": "soil"}) print(pol_eng_dictionary) # outputs: {'kwiat': 'flower', 'gleba': 'soil'} pol_eng_dictionary.popitem() print(pol_eng_dictionary) # outputs: {'kwiat': 'flower'} pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} for item in pol_eng_dictionary: print(item) # outputs: zamek # woda # gleba
  • 17. Module 3 Tuples and dictionaries Key takeaways: dictionaries 4 If you want to loop through a dictionary's keys and values: pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} for key, value in pol_eng_dictionary.items(): print("Pol/Eng ->", key, ":", value) To check if a given key exists in a dictionary: pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} if "zamek" in pol_eng_dictionary: print("Yes") else: print("No")
  • 18. Module 3 Tuples and dictionaries Key takeaways: dictionaries 5 To remove a specific item: pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} print(len(pol_eng_dictionary)) # outputs: 3 del pol_eng_dictionary["zamek"] # remove an item print(len(pol_eng_dictionary)) # outputs: 2 pol_eng_dictionary.clear() # removes all the items print(len(pol_eng_dictionary)) # outputs: 0 del pol_eng_dictionary # removes the dictionary To copy a dictionary: pol_eng_dictionary = {"kwiat": "flower","woda": "water","gleba": "soil"} copy_dictionary = pol_eng_dictionary.copy()
  • 19. Module 3 Tuples and dictionaries LAB Practice 29. Tic-Tac-Toe
  • 20. Congratulations! You have completed Module 3 the defining and using of functions the concept of passing arguments in different ways name scope issues tuples and dictionaries