Your Turn: Expand and Use the Dictionary

  • Add these statements to the end of the script you’ve been building.
  • Name it, and save it.
  • Flash it to the micro:bit.
text = input("Enter score to reach next week: ")
value = int(text)

info['goal'] = value

print("Updated dictionary")
print("info = ", info)

text = info['score']
score = int(text)

text = info['goal']
score_goal = int(text)

difference = score_goal - score

print("That's", difference, "points more.")
  • Click Open Serial and reset the micro:bit.
  • To make it match the example shown here, enter the same values as before, and then enter 2000 when prompted to enter the score to reach next week.
  • Verify that the updated dictionary that gets displayed is info = {'goal': 2000, 'score' : 1234, 'name': 'Sir Lancelot'}.
  • Verify that it displays That’s 766 points more.

Look what happened to the key-value pairs.  The MicroPython runtime interpreter changed the order when you added the goal': 2000 pair.  Again, that change in order did not matter because the script used the 'score' and 'goal' keys to look up the values that got stored in the score and score_goal variables.  Then, the script used these values to correctly calculate:

    difference = score_goal - score
               = 2000 - 1234
               = 766.