Below you will see how to use dictionaries to represent something like a gradebook. Remember that dictionaries contain (key, value) pairs, where every key must be unique. Make sure to pay close attention to how you can create, access, and remove dictionary entries.
To create an empty dictionary, assign a variable to a set of braces:
>>> grades = {}
To add an entry to your dictionary, use this syntax (remember if you are using a string for your keys, they must be in quotes):
>>> grades["Bob"] = 85
>>> grades
{"Bob": 85}
>>> grades["Alice"] = 90
>>> grades["Eve"] = 100
>>> grades
{"Bob": 85, "Alice": 90, "Eve": 100}
To return a value for a given key:
>>> grades["Alice"]
90
To remove an entry:
>>> grades.pop("Bob") # just like .pop() for lists
85
>>> grades
{"Alice": 90, "Eve": 100}
To get either all keys or all values as a list:
>>> grades.keys( )
["Alice", "Eve"]
>>> grades.values( )
[90, 100]
Before accessing a dictionary value always check if the key you are providing exists in the dictionary, otherwise you will get an error:
>>> "Alice" in grades
True
>>> "Bob" in grades
False
>>> grades["Bob"]
Traceback (most recent call last):
File "", line 1, in
KeyError: 'Bob'
We can see that if we try to access a dictionary with a key that doesn't exist we get a key error. Any type of error is very bad and will immediately stop the program from running, so always check if a key exists in a dictionary before accessing the dictionary with a key (unless you're absolutely sure it's there. An easy way to do this is to use my_dict.keys() which returns a list of all of the keys in the dictionary, as explained above).
Search online to find more helpful dictionary methods! Here is a link to the python documentation.
Given a DNA sequence string, calculate the frequency of each base pair (i.e. the number of times that each letter appears in the sequence). Test this function using function number 5.
>>> base_freq("AAGTTAGTCA")
{"A": 4, "C": 1, "G": 2, "T": 3}
Note: you can easily add to the value stored in a dictionary by using the following trick:
>>> grades
{"Alice": 90, "Eve": 100}
>>> grades["Alice"] += 5
>>> grades
{"Alice": 95, "Eve": 100}
Find the most frequent sub-sequence of base pairs of a given length. Using a dictionary will make your life a lot easier! Test this exercise with function number C2 (yeah we know it's not actually a number, but just go with it).
>>> most_freq_seq("AAGTTAGTCA", 3)
"AGT"