Python dictionary article

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:

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

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

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.

Have fun, and please feel free to comment below.

Leave a Repl​​​​​y

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Get the code for the classic Retro Alien Blitz Game using Python Turtle Graphics when you join our mailing list