A dictionary is an object that stores a collection of data with each element being made up of two parts, a key, how you reference the element, and the value that is stored. This is sometimes called a key-value pair.
When you want to access a certain element’s data, you can use the key to reference it. For example, you could use a student number as the key, and then have their name as the value. So if you know a student number, you can find out the student’s name.
A dictionary uses curly braces i.e. {} to contain it’s elements. To build the dictionary you simply define a variable name, and assign a series of key and value pairs within the braces to that variable. A colon is uses to separate the key and the value, and commas are used to separate one pair from another.
For example:
phonebook = {'James':'555-1234','Mary':'555-5678','John':'555-2468','Martha': '555-1357'}
In this example, James is the first key, and 555-1234 is the first value. Where Mary and 555-5678 is the second key-value pair. This continues for each set of keys and values.
If you were print
the variable out, it may or may not be in the order that you entered it. This is because it is not a sequence, like an array, list, or tuple, but a set of data.
In fact, you cannot get data by a numeric index, you have to request the data by the key. Keys also cannot change. Their values can, but the key itself must remain the same for the entire time the dictionary is used. They are immutable.
print(phonebook['James'])
print(phonebook['Martha'])
# won't work - will give a KeyError exception - this happens whenever a key is not found
print(phonebook[2])
Adding an Element to a Dictionary
To add an element to a dictionary variable, all you need to do, is specify the variable, with a key, and assign it a value.
phonebook['Peter'] = '555-0987' #adds a new element in your dictionary object called phonebook
Removing an Element from a Dictionary
There is a del
command, which will remove variables, and in this case, elements from a dictionary.
Just specify the del command, and then the dictionary with the key, and that element is removed.
del phonebook['Peter']
print(phonebook['Peter']) will now generate an error
Data Types in a Dictionary
The data types of a value part of the key value pair can be anything. While we’ve focused on strings mainly so far, they could be numbers, lists, or any other type of data basically.
What is interesting, is that the key can also be different types of immutable data. So we could use numbers, tuples, etc. However, by far, the most common type of data is that of a string. Now, it might be a “number” such as a student number however, most often, numbers like that are stored as a number.
As general rule you only store a “number” as a number, if you are going to use it mathematically (add, subtract, average, min/max, etc). Therefore, zip codes, phone numbers, social security numbers, employee numbers, etc are usually stored as a string, and currency, raw numbers, temperatures, etc. are stored as a number.
Creating an Empty Dictionary
If you need to, you can easily create an empty dictionary and just add items to it later. For example, while reading in a file, you could insert a new element as you loop through the file.
To create an empty dictionary, assign the empty curly braces to a variable name.
sample = {}
sample['David'] = '555-5678'
Loops and Dictionaries
Going through a dictionary is similar to a list. However, since the list doesn’t have a key, and a dictionary does, you have to be able to handle the key. Luckily Python makes it easy to do that.
Using a general form of:
for key in dictionary :
print(dictionary[key])
Notice how we don’t put the key in quotes, this means we are using the variable value of key, not the string literal key. Essentially, we are looping through the list of keys, and then using them to access the values of the dictionary.
phonebook = {'James':'555-1234','Mary':'555-5678','John':'555-2468','Martha': '555-1357'}
for key in phonebook :
print(key + ':', phonebook[key])
Defining Python’s Dictionary Object was originally found on Access 2 Learn