Python Dictionaries

python dictionaries

We’ve covered some cool introductory concepts in Python so far. In learning about Dictionaries and Lists in Python, we found that they were similar. It’s worth taking a closer look at these data types to see how they are similar, and what makes them different as well. Dictionaries optimize element lookups with key value association. They are high performance, fast, and can be updated and mutated as needed. Just putting some code into your editor and testing what results you can get is a great way to get familiar with how these work.

A key difference to understand between dictionaries and lists is that of unordered vs ordered. We saw that in Python lists, there is a specific and defined order. The first item of any given list in Python would be accessed by it’s 0 based key. For example if we had lists by the names of Tesla, Honda, and Subaru – the first value of each of these would be found by interrogating Tesla[0], Honda[0], and Subaru[0] respectively. Really quickly, if we try this out as a test, we can see this is the case.

In lists, the order of the items is used in determining if two lists are the same. This is not the case with dictionaries. In a dictionary, there is no concept of ordering – it is merely a collection of named value pairs. Let’s see a neat example of this difference between lists and dictionaries in code.

This is interesting. Even though the items in the second example, the dictionary are “out of order”, the result is still that these two are equal. Let’s pretend you go into business selling Lego sets. We can make use of a dictionary to help in this goal. We’ll create a starting point of lego sets and their cost in a dictionary named legos. Then we can make use of a while loop to prompt a user for what lego set they are looking for. We will either provide the client the price of the lego set they are looking for, or add it to a back order in our existing dictionary. Let’s try it out.

Here is an example output of our running program.

What lego set do you want?: (q to quit)
Batman Classic
Batman Classic has a cost of 269.99
What lego set do you want?: (q to quit)
Winter Toy Shop
Winter Toy Shop has a cost of 79.99
What lego set do you want?: (q to quit)
Brick Bank
Brick Bank has a cost of 169.99
What lego set do you want?: (q to quit)
Heavy Lift Helicopter
We do not currently have Heavy Lift Helicopter but we can backorder it.
We will add it to our requested inventory.
Lego database updated.
What lego set do you want?: (q to quit)
{‘Batman Classic’: ‘269.99’, ‘Brick Bank’: ‘169.99’, ‘Heavy Lift Helicopter’: ‘customer request backorder’, ‘Firehouse Headquarters’: ‘349.99’, ‘Winter Toy Shop’: ‘79.99’}

We can see that when we quit the program, we actually output the contents of the legos dictionary. When we requested the Heavy Lift Helicopter lego set, it was not in stock. We did however add that item to our database as a customer request. This example just makes use of memory to demonstrate the concept. We would need to store this data to an actual database or the filesystem if we wanted to have a more useful application.

Using in and not in operators with Dictionaries

It is very convenient and English like to check the keys and values of a dictionary. Let’s examine all of our legos.

Note that when checking the keys, you could use something like Brick Bank in legos.keys() however Brick Bank in legos does functionally the same thing, and since the syntax is more concise we can use the shorthand version if we like. There is nothing wrong however with using the longer hand form, since it may be helpful for clarity.

Checking out items(), values(), and keys()

When looping over items in a dictionary, you can customize the data types you extract out using the items(), values() and keys() methods. We can inspect the types that these methods produce, and also go through some examples that show how we can loop over these particular types. Interestingly, when using the type() function to inspect data types in Python, the output resembles an HTML tag with the data type looking like an attribute of that tag.

Creating a Laugh Counting Program

We can make use of a list, a dictionary, a for loop, and the setdefault() method to create a cool little laugh counting program. What it does is to count the number ha, he, and ho words in a list, and calculates the number of times each word occurs in the list. The setdefault() method is a means to check to be sure a key exists in the dictionary.

You can see we have 2 ho’s, 4 ha’s and 3 he’s. Pretty cool!

Making Print Output Pretty

So far in all of the examples of Python we have tested, we have made use of the simple print() function to view output. This is great, but there is no formatting to help the output to be easier to read. To fix this, we can import the pprint module to help us out! We will modify our laugh counting program to make use of pretty print now.

In this case all it does is sort the values properly, but it helps as the output of your dictionaries become larger.

More Examples of Dictionaries in Python

Getting values from a dictionary, and making use of the get() method.

Checking the length of key-value tuples in a dictionary.

Note that the len() function counts each key value pair as one more item. It does not take into account the key and the value separately!

Sorting Keys In Dictionaries

We know that dictionaries in Pythons are unordered. You don’t know ahead of time what order things will come in. If you need to apply an ordering to the keys, you can do so with the sorted() method.

This is a good example of how in the first result, the keys are completely un-ordered. In fact, each time you run the program, those keys are going to come back in a completely different order. By applying the sorted() method to our keys, we can arrange the characters in alphabetical order consistently if needed.

Using the Python items() method to fetch tuples.

How to unpack values in a dictionary

In this snippet we take our handy alphabet dictionary and simultaneously loop over and extract each key and value while also making use of the sorted() method to display a very nice list of our data.

Python Dictionaries Summary

In this article we had a closer look at Python Dictionaries. It is usually implemented as a hash table where a specific hashing algorithm handles the conversion of what is typically a string based key into an integer. The integer is used in the background to find the data a user is looking for. This is because it is faster and has overall higher performance. The values of a dictionary in Python can be any Python object, whether they be built in or user defined objects. The keys of a python dictionary do not have this same attribute. A key can not have the same value as any other key in the dictionary. If there does happen to be more than one of the same key, it is the last key that takes precedence. The keys are also immutable, or they can’t be changed. Dictionaries also have many convenience python functions and methods such as cmp(dict1, dict2), len(dict), str(dict), type(variable), dict.clear(), dict.copy(), dict.fromkeys(), dict.get(key, default=None), dict.has_key(key), dict.items(), dict.keys(), dict.setdefault(key, default=None), dict.update(dict2), and dict.values().