One of the most useful structures in Python is a dictionary. Like lists and tuples, dictionaries are used as a way to store a collection of objects. However, the order of the objects in a dictionary is unimportant. Instead, dictionaries hold information in pairs of data, called key-value pairs. Every key in a dictionary is associated with a single value. Let’s take a look at an example in which we create a dictionary that represents entries in a phonebook:
1 >>> phonebook = {"Jenny": "867-5309", "Mike Jones": "281-330-8004", "Destiny":
2 "900-783-3369"}
3 >>> print phonebook
4 {'Mike Jones': '281-330-8004', 'Jenny': '867-5309', 'Destiny': '900-783-3369'}
5 >>>
The keys in our example phonebook are names of people. Keys are joined to their values with colons, where each value is a phone number. The key-value pairs are each separated by commas, just like the items in a list or tuple. While lists use square brackets and tuples use parentheses, dictionaries are enclosed in curly braces, {}. Just as with empty lists, we could have created an empty dictionary by using only a pair of curly braces.
Notice how, when we displayed the contents of the dictionary we had just created, the key-value pairs appeared in a different order. Python sorts the contents of the dictionary in a way that makes it very fast to get information out of the dictionary (by a process calledhashing), but this ordering changes randomly every time the contents of the dictionary change.
Instead of the order of the items, what we really care about is which value belongs to which key. This is a very natural way to represent many different types of information. For instance, I probably don’t care which number I happen to put into my phonebook first; I only want to know which number belongs to which person. We can retrieve this information the same way as we did with lists, using square brackets, except that we specify a key instead of an index number:
1 >>> phonebook["Jenny"]
2 '867-5309'
3 >>>
We can add entries to a dictionary by specifying the new key in square brackets and assigning it a value:
1 >>> phonebook["Obama"] = "202-456-1414"
2 >>> print phonebook
3 {'Mike Jones': '281-330-8004', 'Obama': '202-456-1414', 'Jenny': '867-5309',
4 'Destiny': '900-783-3369}
5 >>>
We’re not allowed to have duplicates keys in a Python dictionary; in other words, each key can only be assigned a single value. This is because having duplicate keys would make it impossible to identify
which key we mean when we’re trying to find the key’s associated value. If a key is given a new value, Python just overwrites the old value. For instance, perhaps Jenny got a new number:
1 >>> phonebook["Jenny"] = "555-0199"
2 >>> print phonebook
3 {'Mike Jones': '281-330-8004', 'Obama': '202-456-1414', 'Jenny': '555-0199',
4 'Destiny': '900-783-3369'}
5 >>>
To remove an individual key-value pair from a dictionary, we use the del() function (short for delete):
1 >>> del(phonebook["Destiny"])
2 >>> print phonebook
3 {'Mike Jones': '281-330-8004', 'Obama': '202-456-1414', 'Jenny': '555-0199'}
4 >>>
Often we will want to loop over all of the keys in a dictionary. We can get all of the keys out of a dictionary in the form of a list by using the keys() method:
1 >>> print phonebook.keys()
2 ['Mike Jones', 'Jenny', 'Obama']
3 >>>
If we wanted to do something specific with each of the dictionary’s keys, though, what’s usually even easier to do is to use a for loop to get each key individually. Saying “for x in dictionary” automatically gives us each key in the dictionary. We can then use the variable name in our for loop to get each corresponding value out of our dictionary:
1 >>>
We can also use the in keyword to check whether or not a particular key exists in a dictionary:
1 >>> "Jenny" in phonebook
2 True
3 >>> "Santa" in phonebook
4 False
5 >>>
This expression (“x in dictionary”) is usually used in an if statement, for instance before deciding whether or not to try to get the corresponding value for that key. This is important because it’s an
error to attempt to get a value for a key that doesn’t exist in a dictionary:
1 >>> phonebook["Santa"]
2 Traceback (most recent call last):
3 File "<pyshell#1>", line 1,
4 in <module>
5 phonebook["Santa"]
6 KeyError: 'Santa'
7 >>>
If we do want to access a dictionary’s keys in their sorted order, we can use Python’s sorted() function to loop over the keys alphabetically:
1 >>>
Keep in mind that sorted() doesn’t re-sort the order of the actual dictionary; Python has to keep the apparently haphazard ordering of keys in the dictionary in order to be able to access the dictionary keys quickly using its own complicatedhash function.
Dictionaries are very flexible and can hold a wide variety of information beyond the strings that we’ve experimented with here. Although it’s usually the case, dictionaries don’t even have to hold keys or values that are all same types of objects. Dictionary values can be anything, while keys must be immutable objects. For instance, we could have added a key to our phonebook that was an integer object. However, we couldn’t have added a list as a key, since that list could be modified while it’s in the dictionary, breaking the overall structure of the dictionary.
Dictionary values can even be other dictionaries, which is more common than it probably sounds. For instance, we could imagine a more complicated phonebook in which every key is a unique contact name that is associated with a dictionary of its own; these individual contact dictionaries could then include keys describing the phone number (“home”, “work”, custom supplied type, etc.) that are each associated with a “phone number” value. This is much like creating a list of lists:
1 >>> contacts = {"Jenny": {"cell": "555-0199", "home": "867-5309"}, "Mike
2 Jones": {"home": "281-330-8004"}, "Destiny": {"work": "900-783-3369"}}
3 >>> print contacts
4 {'Mike Jones': {'home': '281-330-8004'}, 'Jenny': {'cell': '555-0199', 'home':
5 '867-5309'}, 'Destiny': {'work': '900-783-3369'}}
6 >>> print contacts["Jenny"]
7 {'cell': '555-0199', 'home': '867-5309'}
8 >>> print contacts["Jenny"]["cell"]
9 555-0199
10 >>>
When we wanted to retrieve a specific value inside the dictionary-value associated with the key for Jenny, we had to say contacts[“Jenny”][”cell”]. This is because saying contacts[“Jenny”] now returns the dictionary of numbers for Jenny, from which we have to specify a key for a specific type of phone number.
Finally, there are two alternative ways to create dictionaries that can come in useful in certain specific contexts. You shouldn’t worry about learning the details of how to use them right now, but just be aware that they are a possibility.
When you want to use keys that are strings that only include letters and numbers (i.e., strings that could stand for variable names), you can use dict() to create a dictionary like so:
1 >>> simpleDictionary = dict(string1="value1", string2=2, string3=3.0)
2 >>> print simpleDictionary
3 {'string2': 2, 'string3': 3.0, 'string1': 'value1'}
4 >>>
Here we created a new dictionary named simpleDictionary that has three string keys, but without putting quotes around the key names this time because Python knows to expect strings when we use dict() in this way. We’ll see an example of this use of dict() later in the course.
The second way to use dict() involves providing a list of key-value pairs represented as tuples, like so:
1 >>> simpleDictionary = dict([("string1","value1"), ("string2",2),
2 ("string3",3.0)])
3 >>> print simpleDictionary
4 {'string2': 2, 'string3': 3.0, 'string1': 'value1'}
5 >>>
Within dict(), we include a list (the square brackets), and separated by commas inside that list are tuples (in the pairs of parentheses) that hold each of our key-value pairs. In this case, we aren’t limited to simple string keys; we can again assign any sort of keys we want as long as they are all the same type of object.
NOTE: Keep in mind that, even though dictionaries might seem more complicated to use, their main advantage is that they are very fast. When you’re working with long lists of data, repeatedly cycling through an entire list to find a single piece of information can take a long time; by contrast, looking up the information associated with a dictionary key is almost instantaneous. If you ever find yourself wanting to create multiple lists where items match up across lists based on their ordering, you should probably be using a dictionary instead
Review exercises:
1. Create an empty dictionary named birthdays 2. Enter the following data into the dictionary:
1 'Luke Skywalker': '5/24/19'
2 'Obi-Wan Kenobi': '3/11/57'
3 'Darth Vader': '4/1/41'
3. Write if statements that test to check if ‘Yoda’ and ‘Darth Vader’ exist as keys in the dictionary, then enter each of them with birthday value ‘unknown’ if their name does not exist as a key 4. Display all the key-value pairs in the dictionary, one per line with a space between the name
and the birthday, by looping over the dictionary’s keys 5. Delete ‘Darth Vader’ from the dictionary
6. Bonus: Make the same dictionary by using dict() and passing in the initial values when you first create the dictionary