Counting Letters Using a Python Dictionary

Some Python developers would say that there are two fundamental constructs which form the basis of the language: lists and dictionaries.

Whether or not that is true, they are both certainly very important. All the GCSE Computer Science specifications mention arrays, and although there are technical distinctions, for many purposes the notion that lists are the Python version of arrays will suffice.

Dictionaries are not mentioned in the specifications at GCSE level, but they are such an integral part of Python that any serious student of the language should make a start on learning about them as early as possible. Certainly at A Level they will become very relevant, and will be studied as part of the topic of hashing algorithms.

To help you to gain some familiarity with this important topic, there is some code below that should serve as a basic introduction to Python dictionaries. If you want to get some experience working with this structure, type the code into your favourite editor and run it to see how it works. Then experiment with it and try some ideas of your own. Maybe you could make a small phone book, or an inventory of some kind.

Counting Letters Using a Python dictionary – Listing

def letter_freqs(a_string):
    freqs = {}
    for ch in a_string:
        if ch in freqs:
            freqs[ch] += 1
            freqs[ch] = 1
    return freqs

# A test string
my_string = "supercalifragilisticexpialidocious"

# Get result
result = letter_freqs(my_string)

# Some ways of displaying the result

for (key, value) in letter_freqs(my_string).items():
    print("Character", key, "count: ", value)

The big concept here is the idea of key, value pairs. In some languages dictionaries are called associative arrays as they associate a value with a key. Whatever the name, these structures offer some powerful possibilities for a programmer and are certainly worth learning about.

Have fun, and please feel free to comment below.

Below are products related to this article, some of which may be affiliate links.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *