Python Dictionaries

Some Python developers would say that there are two fundamental data structures which form the basis of the language: lists and dictionaries. Whether or not that is true, they are both certainly very important.

Dictionaries 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.

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.

You are already familiar with the concept of a key, value pair. For example, if you have ever used a phone book to look up a telephone number, the name of the person you were looking for was the key and the value was the number.

Creating a Dictionary in Python

One way to create a dictionary in Python is to use what is called a dictionary literal:

my_dict = {"Bob": "07723 457893",
           "Susan": "07876 238194",
           "Charlie": "07346 985705"}

You don’t need to have a new line for each entry, that is down to personal preference, so you could have

my_dict = {"Bob": "07723 457893", "Susan": "07876 238194", "Charlie": "07346 985705"}

To use the dictionary, one of the most common operations will be to look up the value for a given key, like this:

print(my_dict["bob"])

To help you to gain some familiarity with this important topic, there is an example program 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

This program works by creating a dictionary called freqs and then looping through the characters of the string provided as an argument to the letter_freqs() function. If the current character already exists as a key in the dictionary, its count is increased. Otherwise a new key is created and its value set to 1, meaning this was the first instance of this character encountered.

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


# A test string
my_string = "supercalifragilisticexpialidocious"

# Get result
result = letter_freqs(my_string)

# Some ways of displaying the result
print(result)
print(result.keys())
print(result.values())

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

Have fun, and please feel free to comment below.

Sharing is caring!

Leave a Reply

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