How to use Dictionaries

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, as these are basic and fundamental dictionary operations.

  1. To create an empty dictionary, assign a variable to a set of braces:

    
    >>> grades = {}
                    

  2. 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}
                

  3. To return a value for a given key:

    
    >>> grades["Alice"]
    90
                    

    Or alternately, you can use the get command (which can be handy if you're doing some sort of Higher Order Functions, as in our next lab).

    
    >>> grades.get("Alice")
    90
                    

  4. To remove an entry:

    
    >>> grades.pop("Bob") # just like .pop() for lists
    85
    >>> grades
    {"Alice": 90, "Eve": 100}
                    

  5. To get either all keys or all values as a list:

    
    >>> grades.keys()
    ["Alice", "Eve"]
    >>> grades.values()
    [90, 100]
                    

    Here, the empty parentheses indicate that we are invoking a zero argument function.

    Python 3 users:
    In Python 3, .keys() and .values() return dict_keys and dict_values instead of lists. Luckily, dict_keys and dict_values are iterable, so we can use operators like "Alice" in grades.keys(), or loop with for name in grades.keys(). However, if we want to use other list operations on them, like append, we have to turn them into list objects first. Here's an easy way to do that: list(grades.keys())

  6. 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'
                    

  7. Search online to find more helpful dictionary methods! Here is a link to the python documentation.

Exercise 6: Base Frequency

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 6.


>>> base_freq("AAGTTAGTCA")
{"A": 4, "C": 1, "G": 2, "T": 3}
        

Hint: 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}