4.3 - Functions, Tuples, Dictionaries, Exceptions and Data Processing (PCEP-30)
Write a program that will convert the my_list list to a tuple. (flip) my_list = ["car", "Ford", "flower", "Tulip"] t = tuple(my_list) print(t)
('car', 'Ford', 'flower', 'Tulip')
tuple - example tuple_1 = (1, 2, 4, 8) tuple_2 = 1., .5, .25, .125 print(tuple_1) print(tuple_2) (flip for output)
(1, 2, 4, 8) (1.0, 0.5, 0.25, 0.125)
example 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) (flip card for output)
1 1000 (10, 100, 1000) (1, 10) 1 10 100 1000
2 of 3 pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} print(len(pol_eng_dictionary)) del pol_eng_dictionary["zamek"] # remove an item print(len(pol_eng_dictionary)) (flip for outputs)
3 2
You can create an empty tuple like this: empty_tuple = () print(type(empty_tuple))
<class 'tuple'>
The order in which a dictionary stores its data is completely out of your control, and your expectations. That's normal. (flip)
In Python 3.6x dictionaries have become ordered collections by default. Your results may vary depending on what Python version you're using.
adding a new key; dictionary Adding a new key-value pair to a dictionary is as simple as changing a value - you only have to assign a value to a new, previously non-existent key. (flip)
Note: this is very different behavior compared to lists, which don't allow you to assign values to non-existing indices.
If you want to loop through a dictionary's keys and values, you can use the items() method pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} for key, value in pol_eng_dictionary.items(): *print("Pol/Eng ->", key, ":", value) (flip for output)
Pol/Eng -> zamek : castle Pol/Eng -> woda : water Pol/Eng -> gleba : soil
What is the output of the following snippet? (flip) tup = 1, 2, 3 a, b, c = tup print(a * b * c)
The program will print 6 to the screen. The tup tuple elements have been "unpacked" in the a, b, and c variables.
tuple - example tuple_1 = (1, 2, 4, 8) tuple_2 = 1., .5, .25, .125 (flip)
There are two tuples, both containing four elements.
immutable data; Imagine that a list can only be assigned and read over. You would be able neither to append an element to it, nor remove any element from it. (flip for further explanation)
This means that appending an element to the end of the list would require the recreation of the list from scratch.
You can access tuple elements by indexing them my_tuple = (1, 2.0, "string", [3, 4], (5, ), True) print(my_tuple[3]) (flip)
[3, 4]
For example, you have an English word (e.g., cat) and need its French equivalent. You browse the dictionary in order to find the word (you may use different techniques to do that - it doesn't matter) (flip)
and eventually you get it. Next, you check the French counterpart and it is (most probably) the word "chat".
4 of 4 - example (flip for output) dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} for key in sorted(dictionary.keys()): *print(key, "->", dictionary[key])
cat -> chat dog -> chien horse -> cheval
3 of 3 (flip for output) dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} for english, french in dictionary.items(): *print(english, "->", french)
cat -> chat dog -> chien horse -> cheval Note the way in which the tuple has been used as a for loop variable.
example (flip for output) 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
If you want to get any of the values out of a dictionary, you have to deliver a valid key value: print(dictionary['cat']) print(phone_numbers['Suzy']) (flip for output)
chat 22657854310
2 of 3 (flip for output) dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"} for french in dictionary.values(): *print(french)
cheval chien chat As the dictionary is not able to automatically find a key for a given value, the role of this method is rather limited.
3 of 4 - example (flip for output) dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} for key in dictionary.keys(): *print(key, "->", dictionary[key])
horse -> cheval dog -> chien cat -> chat
tuples prefer to use parenthesis; although it's also possible to create a tuple just from a set of values separated by commas. (flip for further info)
lists like to see brackets
If you want to change the value associated with a specific key, you can do so by referring to the item's key name in the following way: pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} pol_eng_dictionary["zamek"] = "lock" item = pol_eng_dictionary["zamek"] print(item)
lock
If you want to create a "one-element tuple", you have to take into consideration the fact that, due to syntax reasons; a tuple has to be distinguishable from an ordinary, single value; you must "end the value with a comma" (flip for example)
one_element_tuple_1 = (1, ) one_element_tuple_2 = 1.,
A one-element tuple may be created as follows: one_elem_tuple_1 = ("one", ) one_elem_tuple_2 = "one", (flip for additional info)
parenthesis or no parenthesis; but you need a comma for python to know its a tuple. Otherwise it's a variable
2 of 2 pol_eng_dictionary = { *"kwiat": "flower", *"woda": "water", *"gleba": "soil" *} item_1 = pol_eng_dictionary["gleba"] print(item_1) item_2 = pol_eng_dictionary.get("woda") print(item_2)
soil water
"Dictionaries" are unordered*, 'changeable' (mutable), and indexed collections of data
true
"Immutable" datatypes are objects that "cannot be modified or altered" after they have been created
true
"In situ" is a Latin phrase that translates as literally "in position". For example, the following instruction modifies the data in situ: list.append(1)
true
"Mutable" data can be freely updated at any time - we call such an operation "in situ".
true
# Example 1 (didn't put output on next side) tuple_1 = (1, 2, 3) for elem in tuple_1: *print(elem) # Example 2 tuple_2 = (1, 2, 3, 4) print(5 in tuple_2) print(5 not in tuple_2) # Example 3 tuple_3 = (1, 2, 3, 5) print(len(tuple_3)) # Example 4 tuple_4 = tuple_1 + tuple_2 tuple_5 = tuple_3 * 2 print(tuple_4) print(tuple_5)
true
'Tuples' are ordered and unchangeable (immutable) collections of data. They can be thought of as 'immutable lists'. They are written in round brackets
true
'pairs' themselves are "separated by commas" phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310}
true
1 of 2 If you want to access a dictionary item, you can do so by making a reference to its key inside a pair of square brackets (ex. 1) or by using the get() method (ex. 2)
true
1 of 2 You can also insert an item to a dictionary by using the update() method, and remove the last element by using the popitem() method
true
1 of 3 Another way is based on using a dictionary's method named " items() "
true
1 of 3 You can use the del keyword to remove a specific item, or delete a dictionary. To remove all the dictionary's items, you need to use the clear() method
true
1 of 3 There is also a method named " values() ", which works similarly to keys(), but 'returns values'
true
1 of 3; Can dictionaries be browsed using the for loop, like lists or tuples? No and yes.
true
1 of 4 The first of them is a method named keys(), possessed by each dictionary.
true
2 of 3 Items(); returns tuples; this is the first example where tuples are something more than just an example of themselves; where each tuple is a key-value pair
true
2 of 3; No, because a dictionary is not a sequence type - the for loop is useless with it.
true
2 of 4 The method returns an iterable object consisting of all the keys gathered within the dictionary. Having a group of keys enables you to access the whole dictionary in an easy and handy way.
true
3 of 3 Yes, because there are simple and very effective tools that can adapt any dictionary to the for loop requirements in other words, building an intermediate link between the dictionary and a temporary sequence entity
true
3 of 3 pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} pol_eng_dictionary.clear() # removes all the items print(len(pol_eng_dictionary)) # outputs: 0 del pol_eng_dictionary # removes the dictionary
true
A "sequence type" is a type of data in Python which is able to store more than one value; or less than one, as a sequence may be empty; and these values can be sequentially (hence the name) browsed, element by element.
true
A "tuple" is an "immutable" sequence type. It can behave like a list, but it mustn't be modified in situ
true
A hanging indent is a type of indentation where the first line of a paragraph is not indented, but subsequent lines in the same paragraph are indented.
true
As the "for loop" is a tool especially designed to iterate through sequences, we can express the definition as: a sequence is data which can be scanned by the for loop.
true
Assigning a 'new value to an existing key' is simple - as 'dictionaries are fully mutable', there are no obstacles to modifying them.
true
Complete the code to correctly use the count() method to find the number of duplicates of 2 in the following tuple tup = 1, 2, 3, 2, 4, 5, 6, 2, 7, 2, 8, 9 duplicates = tup.count(2) print(duplicates) # outputs: 4
true
Each dictionary is a set of ' key: value pairs '. You can create it by using the following syntax: my_dictionary = { *key1: value1, *key2: value2, *key3: value3, *}
true
Each tuple element may be of a different type (i.e., integers, strings, booleans, etc.). What is more, tuples can contain other tuples or lists (and the other way round).
true
First of all, it's a confirmation that "dictionaries are not lists" - they don't preserve the order of their data, as the 'order is completely meaningless'
true
Fortunately, there's a simple way to avoid such a situation. The "in" operator, together with its companion, "not in", can salvage this situation.
true
Getting a dictionary's value resembles "indexing", especially thanks to the "brackets" surrounding the key's value. Note: if the key is a string, you have to specify it as a string; "keys are case-sensitive": 'Suzy' is something different from 'suzy'.
true
Have you noticed anything surprising? The "order of the printed pairs is different than in the initial assignment". What does that mean?
true
However, you can delete a tuple as a whole: my_tuple = 1, 2, 3, del my_tuple print(my_tuple) # NameError: name 'my_tuple' is not defined
true
IMPORTANT: getting a value from a dictionary you "mustn't use a non-existent key" will cause a runtime error.
true
If you want to get the elements of a tuple in order to read them, you can use the same conventions to which you're accustomed while using lists.
true
It is possible to create an empty tuple - parentheses are required then: empty_tuple = ()
true
Note: each tuple element may be of a different type (floating-point, integer, or any other not-as-yet-introduced kind of data).
true
One of the most useful tuple properties is their ability to appear on the "left side of the assignment operator"
true
Removing the commas won't spoil the program in any syntactical sense, but you will instead get two single variables, not tuples
true
The "dictionary" is another Python data structure. It's "not" a sequence type; but can be easily adapted to sequence processing; and it is mutable.
true
The Python dictionary works in the same way as a bilingual dictionary
true
The dictionary as a whole can be printed with a single print() invocation. phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310} print(phone_numbers)
true
The first and the clearest distinction between lists and tuples is the "syntax used to create them"
true
The list is a classic example of a Python sequence
true
The list of pairs is surrounded by "curly braces" dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
true
The similarities may be misleading - don't try to modify a tuple's contents! It's not a list!
true
This means that a dictionary is a set of key-value pairs
true
To copy a dictionary, use the copy() method: pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} copy_dictionary = pol_eng_dictionary.copy()
true
Tuples are immutable, which means you cannot change their elements; you cannot append tuples, or modify, or remove tuple elements
true
You can loop through a tuple elements (Example 1), check if a specific element is (not)present in a tuple (Example 2), use the len() function to check how many elements there are in a tuple (Example 3), or even join/multiply tuples (Example 4):
true
a dictionary is a one-way tool - if you have an English-French dictionary, you can look for French equivalents of English terms, but not vice versa.
true
a dictionary is not a list - a list contains a set of numbered values, while a dictionary holds pairs of values
true
a key may be any immutable type of object: it can be a number (integer or float), or even a string, but not a list
true
a tuple's elements can be variables, not only literals. Moreover, they can be expressions if they're on the right side of the assignment operator
true
continued In the first example, the dictionary uses keys and values which are both strings. In the second one, the keys are strings, but the values are integers. The reverse layout (keys → numbers, values → strings) is also possible, as well as number-number combination.
true
dictionaries; In Python's world, the word you look for is named a "key". The word you get from the dictionary is called a "value".
true
each key must be unique - it's not possible to have more than one key of the same value
true
example of a tuple my_tuple = (1, 2, True, "a string", (3, 4), [5, 6], None)
true
key-value pairs sandwiched by colons dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
true
mutability - is a property of any of Python's data that describes its readiness to be freely changed during program execution. There are two kinds of Python data: mutable and immutable
true
removing a key; will always cause the removal of the associated value. Values cannot exist without their keys. This is done with the del instruction.
true
the * operator can multiply tuples, just like lists
true
the + operator can join tuples together
true
the len() function accepts tuples, and returns the number of elements contained inside
true
the len() function works for dictionaries, too - it returns the numbers of key-value pairs in the dictionary
true
tuples and dictionaries can work together
true
tuples; the in and not in operators work in the same way as in lists.
true
start of key takessss
ttt
What is the output of the following program? colors = { * "white": (255, 255, 255), * "grey": (128, 128, 128), * "red": (255, 0, 0), * "green": (0, 128, 0) * } for col, rgb in colors.items(): * print(col, ":", rgb)
white : (255, 255, 255) grey : (128, 128, 128) red : (255, 0, 0) green : (0, 128, 0)
To check if a given key exists in a dictionary, you can use the in keyword: pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} if "zamek" in pol_eng_dictionary: *print("Yes") else: *print("No")
yes
You can use the for loop to loop through a dictionary pol_eng_dictionary = { *"zamek": "castle", *"woda": "water", *"gleba": "soil" *} for item in pol_eng_dictionary: print(item) (flip for outputs)
zamek woda gleba
Write a program that will "glue" the two dictionaries (d1 and d2) together and create a new one (d3). (flip) d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'} d2 = {'Mary Louis': 'A', 'Patrick White': 'C'} d3 = {} for item in (d1, d2): *d3.update(item) print(d3)
{'Adam Smith': 'A', 'Judy Paxton': 'B+', 'Mary Louis': 'A', 'Patrick White': 'C'}
To add or remove a key (and the associated value), use the following syntax: phonebook = {} phonebook["Adam"] = 3456783958 print(phonebook) del phonebook["Adam"] print(phonebook) (flip for outputs)
{'Adam': 3456783958} {}
example - adding a new key-value pair to a dictionary dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dictionary['liger'] = 'ligre' print(dictionary)
{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'liger': 'ligre'}
example - removing key dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} del dictionary['dog'] print(dictionary) (flip)
{'cat': 'chat', 'horse': 'cheval'}
example - (flip for output) dictionary = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dictionary['cat'] = 'minou' print(dictionary)
{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}
Write a program that will convert the colors tuple to a dictionary. colors = (("green", "#008000"), ("blue", "#0000FF")) colors_dictionary = dict(colors) print(colors_dictionary)
{'green': '#008000', 'blue': '#0000FF'}
2 of 2 pol_eng_dictionary = {"kwiat": "flower"} pol_eng_dictionary.update({"gleba": "soil"}) print(pol_eng_dictionary) pol_eng_dictionary.popitem() print(pol_eng_dictionary)
{'kwiat': 'flower', 'gleba': 'soil'} {'kwiat': 'flower'}