Python Dictionaries
In the book we covered several Python data types, including the ‘list’. There is one that we didn’t cover, called a ‘dictionary’. Dictionaries can be quite useful, so we thought we would explain them in a blog post.
A dictionary is a way of associating two things to each other. These two things are called the “key” and the “value”. Each item or entry in a dictionary has a key and a value. You will hear these referred to as “key-value pairs”. A dictionary is a collection of key-value pairs.
A simple example is a list of phone numbers. Let’s say you want to keep a list of your friends’ phone numbers. You’re going to use their first names to look up the numbers. (Hopefully none of your friends have the same first name.) The name would be the “key” (the thing you’ll use to look up the information), and the phone number would be the “value” (the thing you’ll look up).
Here’s one way to create a Python dictionary to store names an phone numbers. First, lets create the empty dictionary:
>>> phoneNumbers = {}
Then, let’s add an entry:
>>> phoneNumbers[“John”] = “555-1234”
If we then display our dictionary, it looks like this:
>>> print phoneNumbers
{'John': '555-1234'}
The key is listed first, followed by a colon, then the value. The quotes are there because both the key and the value happen to be strings in this case (they don’t have to be).
Another way to do the same thing is:
>>> phoneNumbers = {“John”: “555-1234”}
Let’s add some more names. Unlike the append() method we used for lists, dictionaries don’t have a method for adding new items. You just specify the new key and value:
>>> phoneNumbers[“Mary”] = “555-6789”
>>> phoneNumbers[“Bob”] = “444-4321”
>>> phoneNumbers[“Jenny”] = “867-5309”
Now, let’s look at the whole dictionary:
>>> print phoneNumbers
{'Bob': '444-4321', 'John': '555-1234', 'Mary': '555-6789', 'Jenny': '867-5309'}
Now, the whole reason we created a dictionary was so we could look things up. In this case we want to look something up by name. You do that like this:
>>> print phoneNumbers[“Mary”]
‘555-6789’
Notice that we use square brackets to specify which key we want within the dictionary. But the dictionary as a whole is enclosed in curly brackets.
A dictionary is somethat like a list, but there are a couple of main differences. Both types are “collections”; that is, they are a way of collecting together other types.
Similarities:
- Both lists and dictionaries can hold any type (even lists and dictionaries), so you can have collections of numbers, strings, objects, even other collections.
- Both lists and dictionaries give you ways to find things in the collection.
Differences:
- Lists are “ordered”. If you put things in a list in a certain order, they stay in that order. And you can sort a list. Dictionaries are “unordered”. If you add things to a dictionary and then display the contents , they may be in a different order than you put them in.
- Items in a list are accessed by their index. Items in a dictionary are accessed by their key.
>>> print myList[3]
‘eggs’
>>> print myDictionary[“John”]
‘555-1234’
As we mentioned in the book, everything in Python is an object, including dictionaries. And dictionaries have some methods that we can use to work with them.
The keys method gives us a list of all the dictionary keys:
>>> phoneNumbers.keys()
['Bob', 'John', 'Mary', 'Jenny']
The values method gives us a list of all the values:
>>> phoneNumbers.values()
['444-4321', '555-1234', '555-6789', '867-5309']
Other languages have things similar to dictionaries. They’re generally called “associative arrays” (because they associate keys and values to each other). Another term you’ll hear for them is “hash tables”.
Just like lists, the items in a dictionary can be any type, including simple types (int, float, string) or compound types (objects) or collections (lists or dictionaries). Yes, you can have dictionaries that contain other dictionaries, just like you can have lists of lists. Actually, that’s not entirely true. It is true for the values in a dicitonary, but the keys are more restricted. If you read the book , you might remember the discussion about “mutable” vs. “immutable” types. Well, dictionary keys can only be immutable types. (booleans, integers, floats, strings, and tuples). You can’t use a list or a dictionary as a key, because these are mutable types.
I mentioned above that one of the things about dictionaries that’s different from lists is that dictionaries are “unordered”. Notice that even though Bob’s number was the third one we added to the dictionary, it was the first item when we display the contents of the dictionary. Dictionaries have no concept of order, so sorting a dictionary makes no sense. But sometimes we want to display the contents of a dictionary in some kind of order. Remember that lists CAN be sorted, so once we get a list of the keys, we can sort that, and then display the dictionary in order of its keys. We can sort the list of keys using the sorted() function, like this:
>>> for key in sorted(phoneNumbers.keys()):
print key, phoneNumbers[key]
Bob 444-4321
Jenny 867-5309
John 555-1234
Mary 555-6789
What if we want to display the items in order of the values instead of the keys? Well, a dictionary is really a one-way lookup. It is meant to look up values using the keys, not the other way around. So it’s a little more difficult to sort by the values. We can do it, it just takes a bit more work:
>>> for value in sorted(phoneNumbers.values()):
for key in phoneNumbers.keys():
if phoneNumbers[key] == value:
print key, phoneNumbers[key]
Bob 444-4321
John 555-1234
Mary 555-6789
Jenny 867-5309
Here, once we got the sorted list of values, we took each value and found its key by looping through all the keys until we found the one that was associated to that value.
Here are a few other things you can do with dictionaries:
Delete an item: del
>>> del phoneNumbers[“John”]
>>> print phoneNumbers
{'Bob': '444-4321', 'Mary': '555-6789', 'Jenny': '867-5309'}
Delete all items (clear the dictionary): clear()
>>> phoneNumbers.clear()
>>> print phoneNumbers
{}
Find out if a key exists in the dictionary: in
>>> phoneNumbers = {'Bob': '444-4321', 'Mary': '555-6789', 'Jenny': '867-5309'}
>>> “Bob” in phoneNumbers
True
>>> “Barb” in phoneNumbers
False
Dictionaries are used in lots of Python code. Remember the “resource files” that are part of Pythoncard programs? If you look at one now, you’ll probably recognize the dictionary structure.
This certainly isn’t a comprehensive overview at Python dictionaries. But it should give you the general idea so you can start using them in your code and recognize then when you see them in other code.