These are the Python data structure demonstrations we did in class on Tuesday, January 26.
For those following along on the Internet: a lot of the order was driven by class questions. We had a good, conversational time, with lots of students asking if you could do different things and the answers coming in the notebook.
Basic scalar types - we can just assign variables.
a_number = 2
a_string = 'hello'
a_boolean = False
The print
function lets us print out variables.
print(a_number)
print(a_string)
We can also use floating-point numbers. Jupyter (the notebook thing I am using) displays the value of the last expression, using the Python syntax that would be required to write it:
a_number = 3.5
a_number
Python has lists as a built-in feature. This creates an empty list.
a_list = []
a_list
And we can add to lists:
a_list.append('squirrel')
a_list
Accessing a list works just like array access in C++ — 0-based indexes:
a_list[0]
An out-of-range index gives us a clean error:
a_list[1]
The len
function tells us the length of a thing for which length is relevant (lists, strings, dictionaries, etc.):
# how big is it?
len(a_list)
We can add more things, and replace existing values using indexing and assignment.
a_list.append('racoon')
a_list[0] = 'skunk'
a_list
We can also directly write lists with their contents.
a_list = ['woozle', 'splintercat', 'left-handed sidewinder']
a_list
Python loops iterate over lists. Each time through the list, the variable animal
is assigned to a different member of the list:
for animal in a_list:
print('I smell a', animal)
animal
If we wanted to iterate by index, like you do in C++, we could do it like this:
for i in range(len(a_list)):
print('I smell a', a_list[i], end=' ')
Python dictionaries map arbitrary keys to values. They are like lists, sort-of, except they work with keys (strings or numbers, usually) instead of integer positions:
a_dict = {'HACKEM MUCHE': 'identify', 'READ ME': 'scare monster'}
a_dict
a_dict['HACKEM MUCHE']
a_dict['FOOBIE BLETCH'] = 'enlightenment'
a_dict
Dictionaries have a method, keys
, that returns a list of keys:
a_dict.keys()
We can sort lists with the sorted
function, that returns a copy of the list in sorted order:
sorted(a_dict.keys())
So, if we want to iterate over the dictionaries contents and print them sorted by key:
for key in sorted(a_dict.keys()):
print('The scroll called {} is {}'.format(key, a_dict[key]))
We can also iterate over the key-value pairs (items) in the dictionary:
for key, value in a_dict.items():
print('The scroll called {} is {}'.format(key, value))
items
actually returns a list of tuples, in this case (key, value)
pairs. We can see this if we dump the items themselves:
for item in a_dict.items():
print('got', item)
The key, value
syntax unpacks the tuples. We know that items
returns a list of 2-element tuples, so we can write 2 variable names separated by commas so we can access them directly.
Also, this loop demonstrates a basic if
statement:
for key, value in a_dict.items():
if key[0] != 'R':
print('The scroll called {} is {}'.format(key, value))
Let's only get the first 2 keys:
for i, key in enumerate(a_dict.keys()):
if i >= 2:
break
print(key)
Python's ‘else-if’ construct is written elif
:
for key, value in a_dict.items():
if len(key) > 7:
print('The scroll called {} is {}'.format(key, value))
elif len(key) < 2:
print('too short')
else:
print("We don't like {}".format(key))
Python has an object None
that represents nothing.
None
You can't really do anything with it.
None + 5
Except test if something is/is not None
:
if a_list is not None:
print('not none!')
This section demonstrates some basic exploration of the Assignment 1 data.
We can load the data. play
will be a dictionary containing all of the play's data:
import yaml
with open('shakespeare/muchado.yaml', 'r') as yf:
play = yaml.load(yf)
play.keys()
Plays have titles:
play['title']
And characters
play['characters']
And acts and scenes - this is the second scene of the first act:
play['acts'][0]['scenes'][1]
Note that the order of the keys is not preserved. Order of lists is.