Learning About Python Dictionaries and Musical Markov Chains

First, some basics about Python dictionaries.

Python dictionaries map a key to a value, and when you have the key, it's fast to look up the value.

The syntax to create dictionaries looks like this

d = {'A': 1, 'B': 2, 'C': 5}

Then, you can look up items at a given key like this:

val = d['C']
print(val)
# 5

Let's apply this to the simplest interesting Markov Chain I could think of:

markov_chain = {'A': ['A', 'G'], 'G': ['A']}

What does this Markov Chain mean? It means that, if the current note is 'A', the next note can be one of 'A' or 'G'. And if the current note is 'G', the next note can only be 'A'.

What will this sound like?

To find out, let's write a program to randomly traverse the Markov Chain, and play notes as we land on them.

import musicalbeeps
import random

random.seed(43)

player = musicalbeeps.Player(volume=0.3, mute_output=False)

markov_chain = {'A': ['A', 'G'], 'G': ['A']}

note = 'A'

for _ in range(16):
    player.play_note(note, 0.5)
    note = random.choice(markov_chain[note])

There's a lot to potentially explain there, but the main thing to notice is how we use random.choice(markov_chain[note]) to select the next note.

Because I used a fixed random seed, the program will always play the same sequence of notes. Specifically: A, A, G, A, G, A, A, G, A, A, G, A, G, A, A, A. If you'd like to hear those notes, try running the program yourself, or check out the companion YouTube video here!

So that's an example of using a Python dictionary to form a musical Markov Chain.

In the next post, I show how to process "Twinkle Twinkle Little Star" to make a Markov Chain.