Python Dictionaries for Frequency Count

What will we cover?

We will learn about dictionaries and how to use them for frequency count.

See the full tutorial on Python Dictionaries as well.

Step 1: What is a Dictionary?

A Python dictionary stores a key-value pair in a mutable data structure.

That sounds crazy, but let’s take a look at how you define them and how they can be used.

my_dict = {
    'Key 1': 'Value 1',
    'Key 2': 'Value 2'
}
print(my_dict['Key 1'])
print(my_dict['Key 2'])

This means you can define key-value pairs between the curly-brackets and look up values with keys.

The keys need to be unique, while the values can be arbitrary. Also, the key and values can be of any type and not only as strings like the above example.

Step 2: The magic of Python Dictionaries

Look at this code.

my_dict = {
    'Key 1': 'Value 1',
    'Key 2': 'Value 2'
}
my_dict['Key 3'] = 'Value 3'
my_dict['Key 2'] = 'Value 3'

If you have a WHAT-moment, I am with you. If not, let’s break it down.

First you define the initial dictionary my_dict. Then you add a new key-value pair (my_dict[‘Key 3’] = ‘Value 3’).

Can you do that?

I am glad you asked. And yes, you can just add as many key-value pairs you want. No questions ask, the Python interpreter will take care of it and add it to the dictionary.

Then the line my_dict[‘Key 2’] = ‘Value 3’ re-assigns the key Key 2 to a new value. And yes, you can do that too.

This is why Python dictionaries are so powerful.

Step 3: Using Python Dictionaries for keeping Records

A normal use-case of Python dictionaries it to keep records of data.

Think of a SQL data base or a Excel spreadsheet with rows of data. Each row has column names with data. For an example see this tutorial.

Such a row can be represented inside a program with a Python dictionary, which is convenient for handling it.

car = {
    'Brand': "Lamborghini",
    'Model': "Sián",
    'Year': 2020
}

The above could represent a line of car brand, model and year from a spreadsheet.

Notice that Year is actually a integer.

Step 4: Frequency count with a Python dictionary

Look at this example where we use a for-loop to iterate over a list.

items = ['Pen', 'Scissor', 'Pen', 'Pen', 'Scissor']
count = {}
for item in items:
    count[item] = count.get(item, 0) + 1

Now that is nice. What happens?

Well we first have a Python list of items and we want to count how many of each items there is.

Then we initialize an empty dictionary with the curly brackets {}.

Can we do that? Yes, and that is why we love Python, it is such a joy to work with for the programmer.

Then we iterate over the Python list and start to update our dictionary. See, this is where the real magic happens. We assign to the key item the number of items already counted added one: count[item] = count.get(item, 0) + 1. The beauty is, that get(item, 0) is looking up if the key item exists in the dictionary, if not, it will return 0.

Think about that. Then it will count the number of occurrences of each unique item in the list.

Also, notice, that you count all the items without knowing any of them before you start.

Step 5: Iterate over a Python dictionary

You might be thinking. This is nice, but can I get the result from the dictionary without knowing the keys?

Assume we continue the example from step 4.

for key, value in count.items():
    print(key, value)

Remember, count is a dictionary, then count.items() returns the key-value pairs in a sequence, hence we can loop over them all.

Similarly, you can iterate over the keys.

for key in count.keys():
    print(key, count[value])

Want more?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Simple Implementation of Caesar Cipher in Python

What will we cover?

We will implement the Caesar Cipher in Python using functions and for-loops.

But wait, we will also describe what the Caesar Cipher is – this will actually help us understand how to solve it with functions.

In the video I will walk you through all you need including how to implement it.

Step 1: Describing Caesar Cipher

  • The Caesar Cipher is a simple substitution cipher, which is limited to only shift the characters by fixed number.
  • Let’s take an example
    • Imagine you got the message: BRX DUH DZHVRPH. What to make out of it. Makes no sense.
    • But what if we get help from this diagram

As you see, the lette B is the first in our cipher message (BRX DUH DZHVRPH).

Above that we find B in the red line and see the letter above is Y on the green line. That means, that the letter Y was encrypted to the cipher letter B.

If you follow along, you will see this is how it works to decrypt the message.

The reverse process will encrypt it.

Step 2: Implement the encryption function

Let’s implement a helper function encrypt_char(char, key) to encrypt a single character, char, with key. What this encrypt function does, is it makes the process above for us. Hence, we have this function to do the process of encrypting one letter.

def encrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + key) % 26)

Then we can implement encrypt_message(message, key), which uses the helper function. Hence, this function below is doing the process of encrypting a whole message.

def encrypt_message(message, key):
    message = message.upper()
    cipher = ''
    for char in message:
        if char not in ' ,.':
            cipher += encrypt_char(char, key)
        else:
            cipher += char
    return cipher

Let’s try it.

encrypt_message("you are awesome.", 3)

Which results in BRX DUH DZHVRPH.

Step 3: Implement the decryption function

This is quite similar.

def decrypt_char(char, key):
    return chr(ord('A') + (ord(char) - ord('A') + 26 - key) % 26)
def decrypt_message(cipher, key):
    cipher = cipher.upper()
    message = ''
    for char in cipher:
        if char not in ' ,.':
            message += decrypt_char(char, key)
        else:
            message += char
    return message

Let’s try it.

decrypt_message('BRX DUH DZHVRPH.', 3)

Then you get YOU ARE AWESOME.

What next?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Master For and While Loops in Python to Create a Hangman Game

What will we cover?

We will cover how to loop over a list. Further, we will learn the power of a While loop. Finally, we will create a Hangman Game.

Step 1: Loop over a list or sequence

Looping over a list can be done as follows (see more about lists here).

my_list = ['First', 'Second', 'Third']
for item in my_list:
    print(item)

This can also be done over a string, which is a sequence.

s = "Rune"
for c in s:
    print(c)
    print("Inside loop")
print("Outside the loop")

Where we notice the syntax of how indentation works. What is inside and outside the loop.

Step 2: While loops and how they differ

Notice that for-loops in Python loop over a predetermined length. In the above cases, the length of the list or length of the string.

If you want a loop the is dependent on something inside the loop.

What do I mean. Let’s take an example.

value = 10
while value > 0:
    value = int(input("Value? "))

As you see – this loop is dependent on input in the loop. If you type zero or negative value, it will stop.

Step 3: Description of the Hangman Game

  • The game is as follows.
  • Computer has a list of words.
  • Computer chooses a random word from the list.
  • The player gets 10 wrong guesses (10 turns).
  • The game follows this loop
    • Computer prints the word character by character replacing with underscore those not guessed yet (initial no characters has been guessed).
    • Player guesses a character.
    • If character is not in word, a turn is withdrawn
    • If no turns left, computer wins.
    • If player has guessed all characters, player wins

Step 4: Implementing the Hangman Game

Let’s try to implement the Hangman Game

import random
words = ['father', 'enterprise', 'science', 'programming', 'resistance', 'fiction', 'condition', 'reverse', 'computer', 'python']
word = random.choice(words)
turns = 10
guesses = ''
while turns > 0:
    print(f"Turns left: {turns}")
    
    guessed_all = True
    for c in word:
        if c in guesses:
            print(c, end=' ')
        else:
            print('_', end=' ')
            guessed_all = False
    print()
    if guessed_all:
        print("You won")
        break
    
    guess = input("Guess a character: ")
    
    if guess in word:
        guesses += guess
    else:
        turns -= 1
else:
    print("You lost")

Step 5: Want more?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Master Python Lists Basics to Create a Jumbled Game

What will we cover?

In this tutorial we will learn Python Lists basics. This will enable us to create a Jumbled Game.

Step 1: Python Lists and Indexing

A Python list is like a list you know it. And the beauty of Python lists is that they can contain anything.

But let’s get started immediately. You can define a list as follows. This list contains strings, but it could contain any types or objects.

my_list = ['Apple', 'Orange', 'Banana']

You get the length of a list by using len().

len(my_list)

Which will return 3.

A list is indexed from 0 – that is you get the first element as follows.

my_list[0]

The second element.

my_list[1]

And it continues as you can guess.

You can index from the end of a list by negative indexing – the last element is indexed by -1.

my_list[-1]

Then the second last element with.

my_list[-2]

Step 2: Get a random element from a list.

Remember the random library we used?

Well, it can be applied on a list.

import random
my_list = ['Apple', 'Orange', 'Banana']
random_item = random.choice(my_list)
print(random_item)

This will pick a random item from the list.

Step 3: Pick random samples from a sequence like a string

Imagine you want to get random samples from a sequence?

What is a sequence, well it can be a string. A string in Python is a sequence.

Then you can pick random samples from it.

letter_sequence = 'abcdefgh'
samples = random.sample(letter_sequence, len(letter_sequence))

Then samples will be a list of unique elements from letter_sequence. Hence, it is all the letters uniquely represented.

Step 4: The Jumbled Game Explained

The jumbled game can be described as follows.

  • A word jumble is a word puzzle game that presents the player with a bunch of mixed up letters and requires them to unscramble the letters to find the hidden word.
  • The computer will take word and jumble it (mix up the letters).
  • Then the player will guess what the word is
  • An initial word list could be: [‘father’, ‘enterprise’, ‘science’, ‘programming’, ‘resistance’, ‘fiction’, ‘condition’, ‘reverse’, ‘computer’, ‘python’]

Step 5: Implement the Jumbled Game

This is straight forward with our competencies.

import random
words = ['father', 'enterprise', 'science', 'programming', 'resistance', 'fiction', 'condition', 'reverse', 'computer', 'python']
word = random.choice(words) 
jumble = random.sample(word, len(word))
jumble = ''.join(jumble)
print(f"The jumble word is: {jumble}")
guess = input(f"Write your guess: ")
if guess.lower() == word:
    print(f"Corret! The {jumble} is {guess}")
else:
    print(f"Incorrect! The {jumble} is {word}")

Want more?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.