Lecture Date: Wednesday, September 14

A dictionary 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.


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.

# Mark Sherriff (mss2x)

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


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

test_average = sum(gradebook['asb2t'])/len(gradebook['asb2t'])
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':10, '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(key) - 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'))

Let's build a language translator!