Lecture 10 - Dictionaries

Lecture Date: Wednesday, February 10

A dictionary (or, very carefully pronounced, a dict) is another mutable collection, like the list. However, there are some key differences that make it more useful in certain situations.

  • A dict is not ordered.
  • A dict is made up of key/value pairs.

Let’s consider a phone book (remember those?). You look up someone’s name and find out their phone number.

So:

phonebook = {‘Mark’:‘434-982-2688’, ‘Amanda’:‘434-234-2566’, ‘Samantha’:‘434-877-3434’}

A typical thing you would do with such a data type is to search it for certain information and add and remove items. Let’s look at some more example code and then we’ll build a more interesting program together.

makingdicts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Mark Sherriff (mss2x)

gradebook = {'mss2x':[99,98,80], 'tbh3f':[89,90,78], 'asb2t':[70,66,73]}

print(gradebook)
print(gradebook['mss2x'])

print('mss2x' in gradebook)
print('lat7h' in gradebook)

test_average = sum(gradebook['asb2t'])/len(gradebook['asb2t'])
print(test_average)
print(format(test_average, "0.2f"))

# Also consider a dictionary as a representation of an entity

employee = {'compid':'mss2x', 'name':'Mark Sherriff', 'dob':'11/09/79', 'year':8, 'room':401}

# methods you should probably know

# clear() - empties the dict
# get() - gets a particular value based on key
# items() - gets all the keys and values
# keys() - gets all the available keys
# pop() - gets a value, and deletes the key/value pair
# values() - gets all the values

# print(gradebook['mst3k']) - Throws an error since it's not there!
print(gradebook.get('mst3k', 'Key not available'))
print(gradebook.keys())

Let’s build a language translator!