CS07 : Building data structures



https://docs.google.com/presentation/d/1Wh3QL7VmlkrFqU0FZ33A-m_sIYYlNfVLRkgUscHzYec/preview
During this topic, you will learn how programming languages group data together into simple data structures like arrays (or lists are they are called in Python) or records (dictionaries). This is the longest topic you have ever seen. Take a deep breath ...

We are learning ...
  • About data structures / structured data types
  • How data structures can be used in practical situations
So that we can ...
  • Use Python to make a simple list of items
  • Perform operations on the list
  • Print out a list in a variety of formats
  • Create lists from other data types and data structures
  • Create two dimensional data structures
  • Use looping to print out two dimensional data structures in a suitable format
  • Search for items in one and two dimensional lists

CGP The Revision Guide Page 49, 50
CGP Exam Practice Workbook Page 60, 61

# Get Ready.png

Activity 1 Lists   I   O   A   E 

https://drive.google.com/file/d/1CJcWp42tyf72ZJGj08vIokf36ZfjhFAm/preview
Click to engage

Humans love lists. We organise ourselves using lists. Computers are good at lists. Look at the following list ...

How many times has he used the word 'list'?


Task 1.1 My Python shopping list
Where we learn how to use Python to create a list of 'things' from scratch


For this exercise, use the Python activities to learn how to use lists before you attempt the summary task. Make sure you type the code snippets in, do not copy and paste! There is no need to evidence your work but you must respond to the challenges which come at the end.


Get read to code

Open up the Python Programming Environment, IDLE.

At the REPL

Store the shopping list in a Python variable by typing the following code, exactly at the prompt and pressing the  Enter key at the end of the line. 

>>> shopping = ['Eggs','Milk','Apples','Leek','Bread']

Do you notice that the list is bounded (surrounded) by square brackets and delimited (separated) with commas? This is how we tell Python that we are giving it a list of values. It might not look as though Python has done anything, but remember, it has stored the list in the computers memory.

Print out the shopping list

Print out your shopping list using this command ...


>>> print(shopping)

Look carefully at the output - it should look the same as the input, including the square brackets.

Print it like a list!

Our shopping list doesn't print out very neatly though, does it? Enter the following at the prompt, pressing  Enter twice at the end of the line.

>>> for item in shopping: print(item)

You have used a loop to walk through every item in the shopping list and print each one out. The way the loop instructions are written should make this fairly clear.

Don't panic!

Print out individual items from the list

Let's print out some of the individual items in the shopping list. We access the list items using the items index like we accessed characters from strings in the last topic. Try the following ...

>>> print(shopping[0])

Not what you expected? In fact, the list indices start at 0 (zero), not 1 (one). Try to access the other items in the list using suitable print commands. However, what happens if you try to type this ...

>>> print(shopping[5])

Can you explain the result? Can you relate what is happening to the way you learnt to print characters from a string out in the last topic? Tell your shoulder partner.

Other useful list functions


Here are some other useful things you can do with lists in Python.


>>> shopping.append('Oranges')  # Now, print out the list again!
>>> shopping[1] = 'Cream'       # Now, print out the list again!
>>> shopping.insert(3,'Beans')  # Now, print out the list again!
>>> shopping.sort()             # Now, print out the list again!
>>> shopping.pop()              # Now, print out the list again!
>>> shopping.pop(3)             # Now, print out the list again!
>>> shopping.append('Bread')    # Now, print out the list again!
>>> shopping.count('Bread')     # Now, print out the list again!
>>> shopping.reverse()          # Now, print out the list again!
>>> shopping.index('Eggs')      # Now, print out the list again!

Now, can you explain what each command does to your shoulder partner?

Didn't you remind me to do that?

Pretty print it!

Finally, print out your shopping list showing the index values using the following little code snippet. Remember to press the
 Enter  key twice at the end of the second line. Type it in carefully.

>>> for index in range(len(shopping)):
      
print(index,':',shopping[index])

Don't worry too much at this stage how the range() function works though you can probably work it out!

Creating empty lists

You can't write out your list of jobs if you haven't got a piece of paper to write them on! In Python, we can easily create an empty list so we can .append() items to it.

Try the following code snippets. You don't have to type the # comments but you do have to hit the  Enter  key twice at the end of the last line ...  

>>> jobs = []                          # Create an empty list
>>> jobs.append('Take out the trash')  # Add a new item to the end of the list
>>> jobs.append('Do my homework')      # Add a new item to the end of the list
>>> jobs.append('Tidy my bedroom')     # Add a new item to the end of the list
>>> for job in jobs : print(job)       # Print out the list

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/login?goto=%2Fstudent
Assignment : CS08 Task 1.1 EASY


Now that you've learnt how to manipulate lists create a list containing the following four film titles ...
  • "Daft and a Little Bit Dafter";
  • "A Room with a Ewe";
  • "From Here to There and Back Again"
  • "Lower Level Lunacy"
Print out your list using the loop method you met in Step 4 but make sure that your variable names are suitable and reflect the contents of the list.

https://repl.it/student
Assignment : CS08 Task 1.1 MEDIUM


Use the list operations from Step 6 to make the following changes to the list ...
  1. Sort the list into alphabetical order;
  2. 'Append' a new film called "The Degradation of the Snood" to the end of the list;
  3. 'Insert' a new film called "Python Incorporated" in the third position in the list (careful!)
  4. Change the name of "Daft and a Little Bit Dafter" to "Daft and a Whole Lot Dafter"
  5. Remove the film called "Lower Level Lunacy" from the list
For the last two tasks, you might have to use the list.index() function to find the position of the film in the list unless you can work it out manually!

Again, use the skills in Step 4 to print out the new list you have made.

https://repl.it/student
Assignment : CS08 Task 1.1 HARD


It would be easy to just work out what was in the list and print the films out using the print() command but that's definitely NOT what I'd like you to try. Using the skill in Step 7 to help you, print out the list using a loop so that the output looks like this ...


Provide evidence that you have printed out the list using a loop in your word processed document.




Task 1.2 Creating lists from other things
Where we learn how to use Python to create lists from other data


You can also use Python to create lists from other things. Use the Python activities to learn how to break up lists before you attempt the summary task. Make sure you type the code snippets in, do not copy and paste! There is no need to evidence your work but you must respond to the challenges which come at the end.


Get ready to code

Open up the Python Programming Environment, IDLE

Break it up!

Type the following commands, pressing the  Enter  key after each line.

>>> message = "Hello and welcome to Python"
>>> letters = list(message)
>>> words = message.split()

Now try printing the contents of the variables letters and words to see what they contain.

>>> print(letters)
>>> print(words)

Can you see what the list() function and the list.split() method does? Can you think of a situation where you might want to use these? Discuss this with your shoulder partner.

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS08 Task 1.2 EASY


Create your own string variable (you make it up), giving it a suitable name (which reflects its contents). Make sure that the string has more than one word in it or the following activities won't work!

https://repl.it/student
Assignment : CS08 Task 1.2 MEDIUM


Use the skills in Step 2 to 'split' up your variable into a separate list of letters and a separate list of words. Print out both lists to show their contents in any way your consider suitable. How does the .split() method decide how to break up the string? Write your ideas down in your word processed document.

https://repl.it/student
Assignment : CS08 Task 1.2 HARD


Use the skills you learnt in Task 1.1 to ...
  1. 'Sort' the list of letters into alphabetical order;
  2. 'Reverse' the list of words.
Print out the new lists to show their contents in any way you consider suitable.




Task 1.3 Joining lists
Where we learn how to use Python to join items in a list together again


Finally, after we've created our list, sorted it, reversed it and generally messed it up, we can join it back together again to give another string. Once again, use the following exercises to investigate how to do this in Python. Make sure you type the code snippets in rather than copying and pasting. There is no need to record what you have done but you will need to respond to the challenge at the end.


Get ready to code

Open up the Python Programming Environment, IDLE

How do you like your eggs?

Type the following commands, pressing the  Enter  key after each line.

>>> eggs = "How do you like your eggs in the morning?"
>>> scrambled = eggs.split()
>>> scrambled.sort()
>>> scrambled.reverse()
>>> scrambled = ' '.join(scrambled)
>>> print(scrambled)

How do the eggs become scrambled? Pay particular attention to the .join() method - what is this doing? Try changing the ' ' to something else, like '-', '_' or even '' and see what happens then.

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS08 Task 1.3 EASY


Create a new string variable, filename, and assign it the value 'Geography Homework Task'. Now convert the string into all lower case (if you can't remember how to do this, look back to the String Manipulation lesson), reassigning the lowercase version to the variable filename .

Print out the value of filename.

https://repl.it/student
Assignment : CS08 Task 1.3 MEDIUM


Now use the skills from Step 2 to ...
  1. 'Split' the string up into a list, reassigning the list to the variable filename;
  2. 'Join' the list items back together again using underscore characters and reassign the string to filename.
  3. Print out the value of filename.
Be careful not to mess with the list by sorting it or reversing it!


https://repl.it/student
Assignment : CS08 Task 1.3 HARD


You may also need to look back at the String Manipulation unit to help you with some of the tasks.
  1. Create an empty list called filename. Look back at Task 1.1 to find out how to do this.
  2. Use an input() statement with a suitable prompt to ask the user to enter the firstWord in the filename and store this in a suitable variable. Convert this word into lowercase.
  3. Append this word to the filename list.
  4. Use an input() statement with a suitable prompt to ask for the secondWord in the filename and store this in a suitable variable. Convert this into it's 'capitalized' form (notice the misspelling).
  5. Append this word to the filename list.
  6. Now join together the items in the filename list using a blank character, '' (not a space!) and reassign this to the filename variable.
  7. Finally, print out your camelCaps filename using a suitable message!

That was kinda the point ...



Demonstrate your understanding

Create a 'cheat sheet' leaflet for Leah to summarise everything that you have learnt during this activity about Python lists. If you can, use a desktop publishing application like Microsoft Publisher - this will enable you to create a Z-fold or a Roll-fold leaflet. If you are not very Publisher literate, you might just have to create your leaflet manually (but you might struggle to put screenshots in!)



Activity 2 Tables   I   O   A   E 

https://drive.google.com/file/d/1VzMN8C0-SwUI1hlOZDPqT2tbdMtYvb0F/preview
Click to engage

The shopping list you worked with in the first activity is a One Dimensional (1D) list. We call a Two Dimensional (2D) list a table - it is a list of lists.


Task 2.1 Movie ratings (manual version)
Where we learn how to collect data, present it in the form of a table and find data within it


https://drive.google.com/uc?export=download&id=19WxOpmVQIClUeDDCebBNryC43Pv-MFli
Click to download

You will be given a copy of a table where you can collect some data on your friends movie ratings. You will have to find 5 friends (I'd struggle) to rate the movies and record their responses in the table.

The ratings should be from 1 (poor) to 5 (excellent)

We store each student’s rating for each movie in the red cells as a number. Unless we provide a key, we need to remember what the numbers mean. Data is only data unless we provide structure, context and meaning in which case it becomes information, remember?  We can reference the cells in the table by using two indices ...

rating[student][movie]

... where student is the number for the students and movie is the number of the movie. Be ready to answer the following questions when you are asked by your teacher.

    1. Find someone who ranked Finding Nemo as the best movie
    2. Find someone who ranked Shrek as the worst movie
    3. Find someone who liked Batman and Finding Nemo equally
    4. Find your ranking for position [2][2] in your table
    5. Find your ranking for position [4][1] in your table



Task 2.2 Movie ratings (automated version)
Where we learn how to use Python to create a table of data and find data within it


One student collected the following data for their ratings table :

https://drive.google.com/file/d/0B83yXMOilskaeS1NQ1gtQ2wwQW8/preview
Click to engage with my answers


For this exercise, use the Python activities to help you to learn how to use two dimensional lists. Make sure you type the code snippets in, do not copy and paste! There is no need to evidence your work, but make sure you read the instructions carefully and discuss the answers with your shoulder partner.

Get ready to code

Open up the Python programming environment, IDLE.

Create a two dimensional list

To store the information from the red cells in a list in Python, type the following code snippet exactly as written at the REPL and press the  Enter  key. Be really careful with the brackets - there are lots of them ...

>>> ratings = [[1,4,3],[5,2,1],[1,2,5],[1,2,4],[1,5,2]]

Notice that each row in the table is stored in it's own little list and each row becomes a single list item in an outer list of columns. You have created a list of lists. Remember, however, that the numbers are just data ...


The two dimensional Python list you have created looks like a one dimensional list because it's all written on one line. You could (and should) try entering the same list in the following way, so it looks like a table! This might make it easier to understand. Enter the following code snippet at the prompt, pressing the  Enter  key after each line. Don't worry about lining up the rows, unless you want to  (like me).

>>> ratings = [[1,4,3],
               [5,2,1],
               [1,2,5],
               [1,2,4],
               [1,5,2]]

Now try printing out the list using a loop like you have done in previous tasks in this lesson by typing in this code snippet, pressing the  Enter  key twice after the line. This is what should happen ...

>>> for rating in ratings : print(rating)

[1,4,3]
[5,2,1]
[1,2,5]
[1,2,4]
[1,5,2]

Locating items in a two dimensional list

The numbers in the list are the values in the table. Before you type the following commands in, remember that the student and the movie we want starts at index 0, not index 1 like it did in the original table. We have to specify the row first followed by the column as separate list indices.

I've done the first one for you but you should try to find the answers to the others yourself ...

    1. Find Beth's rating for Finding Nemo
    2. Find Sandra's rating for Shrek
    3. Find John's rating for Batman
    4. Find Eric's rating for Finding Nemo
    5. Find Lianne's rating for Batman
...
...
...
...
...
>>> print(ratings[2][1])
>>> ____________________
>>> ____________________
>>> ____________________
>>> ____________________
...   prints '2'
...   prints '2'
...   prints '1'
...   prints '2'
...   prints '1'

My new table has been delivered!
I'll run down the stairs and along the hall to the front door!
Imagine this as a picture ...

Create a script to print out a table

Now let's print out the table so it looks like a table! This uses a nested loop - a loop within another loop.
  • The outer loop runs through each row in the ratings table
  • The inner loop runs through each item in each row (essentially the columns)
You need to type this in as a script - choose 'File > New File' from IDLEs menu, save the script and then run it with 'Run > Run Module'. If you are struggling to type it in, the script is available to download - printRatings.py

# Print Movie Ratings


ratings = [[1,4,3],[5,2,1],[1,2,5],[1,2,4],[1,5,2]]

print('           +--------+--------+--------+') # Eleven spaces before the + sign
print('           | Batman | Nemo   | Shrek  |'# Eleven spaces before the | symbol
print('           +--------+--------+--------+'# Eleven spaces before the + sign

student = 1


for row in ratings:
  print(
'Student {0:<3}'.format(student),end='') # Left align student in a 3 character space
  for value in row:
    print('| {0:<7}'.format(value),end='')       # Left align value in a 7 character space
  print('|')
  student = student + 1


print
('           +--------+--------+--------+'
# Eleven spaces before the + sign

This technique also uses a special .format() method to align the content. Have you any idea what the '<' sign, the '3' and the '7' are for? We'll meet this again later in the course.

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS08 Task 2.2 EASY


Use the skills you learnt in Step 2 to create a two-dimensional Python list called diary to store the data in the following table. Remember to put each item in a string by surrounding by quotation marks.


Remember that the data is the values that could change (they are variable) - those shown in the white cells in the table. The headings in the grey cells provide context for the data but are *not* stored in the list!

Print out each row in the diary table using the technique from Step 2.

https://repl.it/student
Assignment : CS08 Task 2.2 MEDIUM


Use the skills you learnt in Task 1.1 Step 7 and Task 1.3 Step 2 to add a section to your script to print out your diary like this ...

Nice!

Hint : You will have to ', '.join() the items in each row from the table inside the print() statement!


https://repl.it/student
Assignment : CS08 Task 2.2 HARD


Bet you thought the medium challenge was hard! Use the skills from Step 4 to add a final section to your script to print out your two-dimensional list like the original table. It should look like this ...

Nicer!

You will have to work out how wide to make the columns from the image and remember to make sure that the variable names you have used reflect their contents - try not to use the same ones as those from the script in Step 4!



Lists can be more than 2 dimensional! A 3 dimensional list
is like a cube, a four dimensional list is beyond (most) human perception!


Demonstrate your understanding

Roy is impressed that you have managed to take a printed table, create a suitable two-dimensional list from it and print it out again like the original table. He is, however, a little confused as to the point. 

Write Roy a explanation of the benefits of storing the list of items like this - think carefully about
  • the possible processing that could be performed on the data
  • the patterns that could be spotted from the data
  • the quantity of data that could be stored
  • how easily the data could be changed if necessary


Activity 3 Dictionaries   I   O   A   E 

https://drive.google.com/file/d/1XRA7SlrqxR_cBj1KfusDv0z8NK5azBWy/preview
Click to engage

When data is stored in a simple array, there is no obvious way in which the data is directly linked to one particular thing. This is where a dictionary comes in. In Python, a dictionary has this structure (look carefully) ...

dictionary = {key:value,key:value,...}


Task 3.1 Creating a simple dictionary
Where we learn how to use Python to create a key : value dictionary to help us search for data


Use the following exercises to learn how Python dictionaries work. There is no need to evidence your work but you must respond to the challenges in the final step. Make sure you type in the code snippet - do not copy and paste!


Get ready to code

Open up the Python programming environment, IDLE.

Create a dictionary dictionary

Copy the following dictionary, pressing  Enter  after every line. Press  Enter  twice at the end. Don't forget the commas at the end of the first, second, third and fourth lines!

>>> definitions = {
      'qualitative':'involving distinctions based on qualities',
      'calisthenics':'light exercises designed to promote general fitness',
      'boardwalk':'a walkway made of wooden boards; usually at seaside',
      'logo':'a company emblem or device',
      'backlash':'a movement back from an impact'
    }

Can see how the key (the word) is linked to its value (the definition)?

Look up a word

Looking up the definition for a word like you would look up a value in a list, except that this time, you don't use the numerical list index, you use the key - in this case the word you want the definition for. For example try the following command at the prompt ...

>>> print(definitions['boardwalk'])

Try looking up some of other words to find the definitions to make sure you understand how the dictionary works.

Printing out my dictionary

To print the contents of a dictionary, you have to use a slightly different method than for simple lists. Try the following, pressing the  Enter  key after each line and twice at the end ...

>>> for key, value in definitions.items():
      print(key,':',value)

... or to print it more pleasingly, try this ...

>>> for key, value in definitions.items():
      print('{0:<17} : {1}'.format(key.capitalize(),value.capitalize()))

Rubber duck this to your shoulder partner to make sure you understand what the code is doing. Look carefully - do you notice anything strange about the order that the definitions print out in?


This is due to the way in which Python stored the values in the dictionary. In fact, it doesn't usually make sense to print out the values in a dictionary at all - dictionaries are intended to make searching easier, but if we did want to print out the definitions in sorted order, we could do this (there is no need to type the # comments) ...

>>> keys = list(definitions.keys())
>>> keys.sort()
>>> for key in keys:
      print('{0:<17} : {1}'.format(key.capitalize(),definitions[key].capitalize()))

Again, rubber duck this to your shoulder partner - pay particular attention to the emboldened text and how it is different from the last example.

Adding to or changing items in a dictionary

Again, the technique for dictionaries is slightly different to that for lists. If the key is not in the dictionary, the following command will add it in together with its value.

>>> definitions['vermivorous'] = 'eating worms'

Now try printing out the dictionary using any of the techniques from Step 4 to see the change you've made.

If the key is already in the dictionary, the following command will change its value ...

>>> definitions['logo'] = 'a company emblem or device which identifies the company'

Again, try printing out the dictionary again to see how it has changed.

Removing items from a dictionary

Again, the technique is slightly different from lists. This technique will give an error if the key is not in the dictionary. To remove the definition for 'backlash' try entering the following command, pressing the  Enter  key after the line.

>>> del(definitions['backlash'])

Now try printing out the contents of the dictionary again.

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment  : CS08 Task 3.1 EASY


Create a Python dictionary called keywords and store the definitions for the keywords for this topic. You will have to use the Computer Science Key Terms list to help you - remember that the keywords are in bold red. You can start your dictionary like this ...

keywords = {
  "list":"A collection of elements with an inherent order."
}

Print out your list of keywords using any of the techniques from Step 4.

https://repl.it/student
Assignment : CS08 Task 3.1 MEDIUM


Use an input statement to ask the user which definition to print. Test that this works but make sure that you only ask for a definition which is definitely in the dictionary - we haven't learnt how to check if it's not there yet! (You'll get a KeyError if you try to print a keyword that's not there.)

Remember that Python is case sensitive so how could you handle the user entering mixed case words whilst still retrieving the correct definition? Try to incorporate this into your script if you can.


https://repl.it/student
Assignment : CS08 Task 3.1 HARD


Finally, your program should perform the following tasks on the dictionary ...
  1. Ask the user for a new keyword definition to ADD to the dictionary. First, use an input statement to ask for the word and a second input statement to ask for the definition and add the new keyword and its definition to the dictionary using the technique shown in Step 5.
  2. Ask the user for a keyword definition to CHANGE. First, use an input statement to ask for the keyword to change and then a second input statement to ask for the new definition. Make sure that you test this by entering a keyword that is already in the dictionary and update the value in the dictionary using the technique shown in Step 5.
  3. Finally, ask the user for a keyword to DELETE from the dictionary. Use an input statement to ask for the word and remove it from the dictionary using the technique shown in Step 6.
Finally, print out your dictionary using any of the techniques from Step 4.






Task 3.2 Creating records using a dictionary
Where we learn how to use Python to make a simple database table using a dictionary


https://drive.google.com/uc?export=download&id=1cLjToermgySVYR0T9ZFwKY7J_eIahGHg
Click to download

Groups of related data which are tied to one key value are called records and are the building blocks of databases. To complete this task, you will be given a table with space to find and record the details of 5 of your classmates.


Get ready to code


Open up the Python programming environment, IDLE.

Store your friends characteristics

Consider this sample set of student characteristic ...


In this case, the key should be the persons name and the value will be the four characteristics stored as a list. This is what the table of data would look like when stored as a dictionary ...

>>> students = {
      'Simon' :['14','Green','Dark Brown','ML'],
      'Graham':['13','Hazel','Blonde','FJ']
    }

Notice how the numbers are stored as strings - this will be important when we come to print out our dictionary later on. Can you think how you might add more rows to this data structure? 

 Retrieving characteristics from the dictionary

If we wanted to find Simon's eye colour (index 1 in the value list), we could type a command like this ...

>>> print(students['Simon'][1])

Could you find Simons hair colour? What about Grahams Tutor group?


Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS08 Task 3.2 EASY


Use the data you collected at the beginning of the task to create a dictionary of records to store the details of your five friends. Print out the dictionary using any of the techniques from Task 3.1 Step 4.

https://repl.it/student
Assignment : CS08 Task 3.2 MEDIUM


When you printed out your dictionary of friends in the Easy challenge, the value would have been a list and looks a bit odd when its printed. Try printing out the contents of the dictionary so that it looks mine ...

Hint : Look back at Task 1.3 for help ...

https://repl.it/student
Assignment : CS08 Task 3.2 HARD


Create a series of input statements to collect the data for one more person. Use all the skills you have learnt about lists and dictionaries to add the new record to the dictionary. It's a good idea to let someone else sit at your computer and test out your new script and give you some feedback.

Finally, print out your new dictionary in key order (look back at Task 3.1 Step 4).



Demonstrate your understanding

Sheila is impressed that you've managed to get to grips with dictionary data structures - she's heard that they can be a bit tricky! She would like to have a handy reference guide so that she can refer to it when she needs to point the programmers in the right direction.

Use a presentation package to produce a presentation with the following slide titles ...
  • What is a dictionary?
  • How do I create a simple dictionary?
  • How do I print a dictionary?
  • How do I alter a dictionary?
  • How do I store records in a dictionary?
Use the examples from your programming challenges to help you.


Activity 4 Looking for things  I   O   A   E 

https://drive.google.com/file/d/1dhmMuop2xrFe3iBdaYCBEGKRNERT5pT2/preview
Click to engage

So, we've pretty much learnt how to store anything we want in a list or a dictionary, but what if we want to know whether something is in our list before we meddle with it? Behold the incredibly useful keyword ...

It's beautiful ...


Task 4.1 Keep looking ...
Where we learn how to use the Python 'in' operator to look for things in lists and dictionaries


For the following tasks to work, you need to make sure that you have created the simple list and the dictionary using the script from Step 1. There is no need to evidence your work at this stage, but make sure that you type in the commands and discuss what happens with your shoulder partner.


Get ready to code


Download the script my family and other pets.py and save it in a suitable place in your documents. Find the file, right click on it and choose 'Edit with IDLE'. This is what the script should have in it ...

This is not really my family, or my pets

Run the script by pressing F5 (or choosing 'Run > Run module' from the IDLE menu. The list and the dictionary will load into memory and you will be given the prompt back.

Interrogate the list and the dictionary

I'm so forgetful! I've forgotten who is in my family and what my pets are called! Try typing the following commands at the prompt, remember to press the  ENTER  key after each one. I've not shown you the output on purpose ...

>>> 'oliver' in family
>>> 'mark' in family
>>> 'dolly' in pets['cats']
>>> 'bob' in pets['fish']

Now practice looking for different family members and pets in the list and the dictionary. NOTE : You are not really asking questions here, you are making assertions which you firmly believe to be True ...

... but I'm afraid your assertion is 'False'!

We can make the output a little more friendly as well using a simple selection statement. If you are familiar with Python selection statements, the syntax might look a little odd, but it still makes sense when you read it ...

>>> print('Oliver is in your family') if 'oliver' in family else print('Who?')
>>> print('Mable is your dog') if 'mable' in pets['dogs'] else print('Who?')

Rubber duck these two lines to your shoulder partner - they make more sense if you read them out. This isn't the same way we will structure selection statements in future but it's the only way you can write them on a single line.

Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS08 Task 4.1 EASY


Create your own list and your own dictionary to store some details about your life. Be inventive and try not to use the categories I've used. This is mine (and you can't copy it) ...


https://repl.it/student
Assignment : CS08 Task 4.1 MEDIUM


Have another go at printing out the list and printing out the dictionary in a nice, attractive way. Look back at Activities 1, 2 and 3 to remind yourself how to do this.

Again, to help you, this is what mine looks like ...


https://repl.it/student
Assignment : CS08 Task 4.1 HARD


Now you are going to create a really simple (!) search script. I'm not going to give you much help with this (you'll be pleased to know) but I am going to show you what the output should look like for my script ...


It is meant to be hard!



Demonstrate your understanding

To be honest, if you've managed to do the Hard challenge, you've probably demonstrated as much understanding as is humanly possible and Erma is extremely impressed. If you did manage the Hard challenge, print out your script and annotate it as much as you can to explain how it works.


Assessment Task (Homework)

Look carefully at the following store receipt from my shopping trip to Bicester.


The information held in this receipt could be stored in a 2D list starting at index value 0 containing a simpler list which could look like ['Fresh Milk',0.81]. With this in mind, answer the following questions.
  1. Write down the list which appears at index 6.
  2. In the Fresh Milk example, why is Fresh Milk in quotation marks whereas 0.81 is not?
  3. Write out the Python code which you would use to define a list which contains the first 5 items from this till receipt. Call the list receipt.
  4. Suggest three facts that you could infer about me from the items that I have bought.
  5. Write down an algorithm (the steps involved) for calculating the receipt total and the change.
Grading rubric

MASTER :  Your answers to the five questions are clear and concise. You have made some remarkably accurate judgements about me from my purchasing habits.
APPRENTICE I'm satisfied that you understand the concept of a list, however, your responses are not clear and you have made some errors. I don't recognise myself from your comments.
NOVICE : You have major gaps in your understanding of lists and this shows in the answers to the questions. Your algorithm is simplistic and could lead to errors in calculation of the receipt total and possible sackings. Your judgements about my lifestyle are wacky, to say the least.

Click to download revision cards
https://docs.google.com/document/d/1eiZK-eMALS0nlBzq-QifVXm2qaL5y19geB2tZ5fzShw/export?format=pdf
Remember to print them single sided

# Flash cards.png
Click to load key word list to help you make your own flash cards 

https://goo.gl/forms/yAX9mzrTUod67MfA3
Try to get 5/5!


Hungry for more?

Check out these lists of words at the Oxford Dictionaries website. Have a particular look a the section on 'Weird and wonderful words' - there's some crackers in there!