Dictionary Basics

  1. Write code to create a dictionary grades that maps a student’s name to their assignment grade. grades has two entries in it:

    Sam Reimer –> 84.3

    Steve Bardeau –> 90.5

     
    1
    # replace this comment with your code
    2

    (dict1)

    You create a dictionary with { and }, and you put entries in it separating the key from the value with :.
    2
     
    1
    grades = { 'Sam Reimer': 84.3, 'Steve Bardeau': 90.5 }
    2

    (dict1_a)

2
grades = { 'Sam Reimer': 84.3, 'Steve Bardeau': 90.5, 'Colette Gonzales': 94.5 }

(dict2_pre)

  1. Write code to retrieve from dictionary grades the grade of ‘Colette Gonzales’. Store her grade in a variable colette_score.
    2
     
    1
    # replace this comment with your code
    2

    (dict2)

    Suppose you have a dictionary aDict. You can print the value with key key by doing print(aDict[key])
    2
     
    1
    colette_score = grades['Colette Gonzales']
    2

    (dict2_a)

  1. Write code to map floating point numbers to strings in a dictionary posOrNeg, initially containing these entries:

    -3.14 –> ‘negative’

    40.79 –> ‘positive’

    0.01 –> ‘positive’

    2
     
    1
    # replace this comment with your code
    2

    (dict3)

    You create a dictionary with { and }, and you put entries in it separating the key from the value with :.
    4
     
    1
    posOrNeg = { -3.14: 'negative',
    2
                 40.79: 'positive',
    3
                  0.01: 'positive' }
    4

    (dict3_a)

  1. Given a dictionary grades, write code to add an entry mapping John Fleenor to the grade 92.5.
    2
     
    1
    # replace this comment with your code
    2

    (dict4)

    After a dictionary has been created you add entries using the syntax:

    aDict[key] = value

    2
     
    1
    grades['John Fleenor'] = 92.5
    2

    (dict4_a)

  1. Given a dictionary grades containing a mapping of Sam Reimer to the grade 84.3, update the dictionary to change the grade to 94.3.
    2
     
    1
    # replace this comment with your code
    2

    (dict5)

    After a dictionary has been created you can update an entry using the syntax:

    aDict[key] = value

    (Just like creating a new entry.)

    2
     
    1
    grades['Sam Reimer'] = 94.3
    2

    (dict5_a)

  1. Given a dictionary grades containing a mapping of Sam Reimer to a floating point number, write code to add 1 to the grade.
    2
     
    1
    # replace this comment with your code
    2

    (dict6)

    Your code will have to access the value, add one to 1, and then update the entry. This can be done in one line of code.
    2
     
    1
    grades['Sam Reimer'] = grades['Sam Reimer'] + 1
    2

    (dict6_a)