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.

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.

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.

Leave a Reply