Chapter 2: Lecture 4
• Dictionary
• Characteristics of a dictionary
• Creating a dictionary
• Using a dictionary
• Exceptions
• Activities
Characteristics of a dictionary?
• A dictionary is not a sequence data type but is mutable.
• The Python dictionary works in the same way as a bilingual dictionary
• For example, you have an English word, such as cat and need its French equivalent
• You browse the dictionary to find the word cat
• Next, you check the French equivalent, and it is the word "chat"
• In Python, the word you look for is called a key → cat
• The word you get from the dictionary is a value → chat
Characteristics of a dictionary?
• A dictionary is a set of key-value pairs
• Each key must be unique - no more than one key of the same value;
• A key may be any immutable type of object – integer, float or even a string, but not a list
• A dictionary is not a list – it holds pairs of values
• The len() function returns the number of key-value elements in the dictionary
• A dictionary is a one-way tool
• An English-French dictionary provides French equivalents of English terms
• It cannot provide the English equivalents of French terms
English word French equivalent word
Creating a dictionary
• A dictionary is created using initial key-value pairs enclosed in curly brackets
• For example:
• In the first example, keys and values are both strings
• In the second case, the keys are strings, but the values are integers
• Curly brackets surround the key-value pairs, commas separate pairs, and colons separate the
key-value pairs.
Creating a dictionary
• The dictionary can be printed with a single print()statement
• The order in which a dictionary stores its data is irrelevant
• In Python 3.6x and higher, dictionaries have become ordered collections by default.
• The ordering is based on the key
• To get any of the values, a valid key is required:
Using a dictionary
• To print the key-value pairs in a dictionary, the for loop can be used:
Using a dictionary
• It is possible to search for keys in a dictionary and print the corresponding pairs
• For example:
Using a dictionary
• It is best practise to align code vertically to make it code more readable:
• For example:
Using a dictionary
• Instead of searching a dictionary for specific keys, the method keys() can be used
• It returns an iterable object consisting of all the keys gathered within the dictionary
• A group of keys allows access to the whole dictionary in an easy way
• For example:
Using a dictionary - the items() method
• The method items() returns tuples where each tuple is a key-value pair
• Each key-value pair is treated as an item
• For example:
Using a dictionary - values() method
• The method values() returns dictionary values
• In each key-value pair, the value is identified
• For example:
Using a dictionary - modifying and adding values
• Dictionaries are mutable, and there are no obstacles to modifying them
• To replace the value "chat" with "minou“ we use the following code:
Using a dictionary - modifying and adding values
• A new key-value pair can be added to a dictionary as follows
• An item can be inserted to a dictionary using the update()method
Using a dictionary – removing a key
• A key can be removed from a dictionary using the del instruction
• The entire key-value pair is removed
• To remove the last item, the popitem() method is used
Exceptions
• Writing error-free code is not an achievable goal
• Even the most careful programmer is not able to avoid minor or major defects
• Programming errors have two sources:
• Bad data fed to the code
• Mistakes in the program – bugs causing undesirable code behaviour
• In the code below, entering a value that is not an integer will result in an error
Exceptions
• The exception that causes the code to stop is ValueError.
• How do you protect the code from termination due to incorrect data entry?
• We could check if the data entered by the user is valid
• In this case, we expect the input string to contain digits only - integers
• The check itself may look like this:
Exceptions - the try-except branch
• The programmer’s rule:
• “It is better to handle an error when it happens than to try to avoid it".
• The format for the try-except branch is as follows:
• The try block – code suspected to be risky and may terminate the running code in
case of error, is placed here
• The except block - designed to handle the exception by displaying an error message
Exceptions - the try-except branch
• The new version of the previous code is:
• The code does not terminate unexpectedly
• Any error which occurs does not terminate program execution
• When either the try block or the except block is executed successfully, the
control returns to the normal path of execution
• Is ValueError the only way the control could fall into the except branch?
Exceptions - dealing with more than one exception
• It is possible to have two exceptions after one try in the previous example:
Exceptions – some useful exceptions
• Below are some useful exceptions:
Exception Description
ZeroDivisionError Appears when forcing Python to perform any operation which provokes division in which
the divider is zero, or indistinguishable from zero. Possible operators are: /, //, and %.
ValueError Occurs when dealing with values which may be inappropriately used in some context.
Raised when a function (like int() or float()) receives an argument of a proper type, but its
value is unacceptable.
TypeError Shows up when applying a data whose type cannot be accepted in the current context. For
example:
short_list = [1]
one_value = short_list[0.5]
AttributeError Arises when trying to activate a method which does not exist in an item under
consideration.
SyntaxError Raised when the control reaches a line of code which violates Python's grammar.
Activities
1. What is the output of the following program?
2. What is the output of the following program?
Activities
3. What is the output of the following program?
4. What is the output of the following program?
Activities
5. Write a Python program to add a key to a dictionary.
6. Write a program to concatenate the following dictionaries to create a new one.
Activities
7. Write a Python program that prompts the user to input an integer and displays
the value entered. However, the program should raise a ValueError
exception if the input is not a valid integer.
8. What will be the output of the following Python code if the input entered is 6?