Create a Dictionary

Let's make a simple interactive dictionary with two key-value pairs.

Example script: interactive_dictionary

  • Enter, save, and flash the script simple_dictionary:
# interactive_dictionary

from microbit import *

sleep(1000)

string = input("Enter your name: ")

text = input("Enter a recent game score: ")
value = int(text)

info = {   }

info['name'] = string
info['score'] = value

print("Dictionary")
print("info = ", info)

name_val = info['name']
text = info['score']
score_val = int(text)

print("Hello", name_val, "your score was", score_val)

 

  • Click Open Serial.
  • In the terminal, follow the prompts to enter a name and a score. 

Assuming you entered Sir Lancelot for the name and 1000 for the score, the terminal should respond with info = {'name': 'Sir Lancelot', 'score' : 1000} on one line and Hello Sir Lancelot your score was 1000 on the next.

  • Verify that the terminal response is consistent with your input.

 

How interactive_dictionary Works

The script starts by storing your keyboard input into the string and value variables.  Let’s assume you typed Sir Lancelot and 1000 in response to the prompts.  The string variable will store 'Sir Lancelot', and the value variable will store 1000.  

string = input("Enter your name: ")

text = input("Enter a recent game score: ")
value = int(text)

This statement creates an empty dictionary and names it info.

info = {   }

Since the dictionary does not already have 'name' or 'score' keys, these two statements add two key-value pairs to the dictionary.  Assuming the string variable stores 'Sir Lancelot' and the value variable stores 1000, one key-value pair would be 'name': 'Sir Lancelot', and the second would be 'score' : 1000.

info['name'] = string
info['score'] = value

The first print statement is just a heading.  The second one displays info = and then the contents of the dictionary.  Continuing the Sir Lancelot example, it would look like this: info = {'name': 'Sir Lancelot', 'score' : 1000}

print("Dictionary")
print("info = ", info)

The first two statements here “look up” values in the dictionary by using their keys.  The name_val variable stores the value that’s paired with 'name' in the dictionary.  Continuing the earlier example, name_val would store the string value 'Sir Lancelot' and score_val would store the int value 1000.

name_val = info['name']
text = info['score']
score_val = int(text)

After looking up the values and storing them in variables, the script uses a print statement to display “Hello Sir Lancelot your score was 1000”.

print("Hello", name_val, "your score was", score_val)