Block 3 Part 2 - Python Code Flashcards
Create the following list as a variable:
a_list
items: 1, 10, 23, 2
a_list = [1, 10, 23, 2]
Check the length of the list.
len(a_list)
Add the number 5 to the end of the list.
a_list = a_list + [5]
Check the value of the last element in a_list.
a_list[len(a_list) - 1]
Display a_list on the screen
a_list
True or false?
Dictionaries – just like any other data items – are objects with an id, type and value.
True
Here is an example of a Python dictionary:
mini_dictionary = {‘train’: ‘A powered
railway vehicle’, ‘bicycle’:
‘A vehicle consisting of
two wheels’}
Look at the syntax.
What’s different in a dictionary to a list?
How many key-value pairs does this dictionary have?
Item are surrounded by {} instead of brackets.
Word has apostrophes, e.g. ‘word’.
It has two key-value pairs:
train + definition
bicycle + definition
True or false?
Dictionaries have something in common with lists: they are both containers.
True
Can we create an empty dictionary?
Yes - it might look something like this:
train_types = {}
Adding items to a Python dictionary
Once you have initialised the dictionary
e.g. population_millions = {}
Use the following code in the shell to add key-value pairs.
population_millions[k___] = v_____
key
value
Accessing dictionary values
For accessing the values of a dictionary, you can use the k_____, just like you can use an index to access an item in a list.
For instance, in order to access the item with the key key from dictionary population_millions, use:
population_millions[key]
Q: What would you type if you wanted to
access the input for the USA?
Q: What output would you get?
keys
population_millions[‘USA’]
319 (As per my previous input)
True or false?
Strings are not case-sensitive, so when accessing dictionary items it’s okay if you write, for example, ‘india’, rather than ‘India’.
False - they are case sensitive so be sure to write it correctly.
Amending a dictionary
To amend a dictionary entry, simply type it in again.
E.g. First entry
population_millions[‘France’] = 670
correct to 67, type again
population_millions[‘France’] = 67
It simply o_________ the previous value.
overwrites
Checking for a key
Sometimes it is useful to check whether a dictionary contains a particular key, before you try to access the value via that key. Why? If a key doesn’t exist, using the key results in an e______ message. If you are using the key in a program, the execution of the program will s_____.
error message
stop
Checking for a key
To check for a key in a dictionary, use the shell and type the following code:
key in population_millions
e.g. ‘USA’ in population_millions
Q: What output will we get if it is there?
True