Lecture 10 Data Structures
Lecture 10 Data Structures
STRUCTURES
REVIEW: WHAT ARE DATA
STRUCTURES?
In computer science, a data
structure is a particular way of
organizing data in a computer so that
it can be used efficiently.
REVIEW: LISTS
A List is a kind of Collection
single “variable”
A collection is nice because we can carry many
>>> t1 = [1, 2]
>>> t1.append(3)
>>> print(t1)
[1, 2, 3]
LIST INSERT METHOD
>>> l = [1, 2]
>>> print(l)
[1, 2, 4]
LIST INSERT METHOD
>>> l = [1, 2]
>>> print(l)
[1, 2, 4]
LIST INSERT METHOD
>>> l = [1, 2]
>>> print(l)
[1, 4, 2]
LIST METHODS
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1,2,3]
>>> print(t2)
None
‘is’ OPERATOR
Given two strings
a = ‘banana’
b = ‘banana’
key-value pair
DICTIONARY
Lists index their entries based on the position
in the list.
Dictionaries are like bags - no order
>>> eng2sp = {}
dict()
>>> print(eng2sp)
{}
DICTIONARY
>>> print(eng2sp)
{'one': 'uno'}
DICTIONARY
>>> print(eng2sp)
>>> item_price = {}
>>> item_price[‘milk’] = 10
>>> print(item_price[‘milk’])
10
DICTIONARY
>>> item_price = {}
>>> item_price[‘milk’] = 10
>>> print(item_price[‘sugar’])
KeyError: ‘sugar’
DICTIONARY
>>> number_of_days[‘February’]
DEBUGGING
Key Error
KeyError: 3
ITERATION ON
DICTIONARIES
Even though dictionaries are not stored in
order, we can write a for loop that goes
through all the entries in a dictionary -
actually it goes through all of the keys in the
dictionary and looks up the values
ITERATION
eng2sp = {'one': 'uno', 'two': 'dos',
'three': 'tres'}
for k in eng2sp:
print(k)
ITERATION: VALUES
eng2sp = {'one': 'uno', 'two': 'dos',
'three': 'tres'}
for k in eng2sp:
print(eng2sp[k])
‘in’ OPERATOR
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three':
'tres'}
>>> counts.values()
>>> counts.items()