KEMBAR78
Python PCEP Tuples and Dictionaries | PPTX
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

Python PCEP Tuples and Dictionaries

  • 1.
    Tuples and dictionaries Module3 Functions, Tuples, Dictionaries, Data processing
  • 2.
    Module 3 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand 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 Tuplesand dictionaries LAB Practice 29. Tic-Tac-Toe
  • 20.
    Congratulations! You have completedModule 3 the defining and using of functions the concept of passing arguments in different ways name scope issues tuples and dictionaries