A standard data structure in computer science is the “associative array” which is also called a “map.” In Python, this structure is called a “dictionary.” so you guessed it, this article is about Python Dictionaries.
Dictionaries are used when you have key/value pairs of data – an input which is mapped to an output.
Suppose we are creating a new social network called “Friendface” where any life form or intelligent agent is allowed to join.
Read also: Python lists, Tuples, Sets and Dictionaries to know the differences between them.
Using Python Dictionaries
Let us make our first post to Friendface… We will use this post to show you how to create a dictionary. To begin, we will collect several pieces of data for each post: The user id… message… language… datetime… and the location from whence the post was made. Using dictionaries, we can store all of this data in a single object.
To create a dictionary, use the left brace, then list the key name, a colon, and the value. If you have more than one key/value pair, you separate them using a comma.
Once you have finished entering your data, use a right brace to finish the dictionary. We have created a dictionary called ‘post’ with 5 pieces of data. If you think of a dictionary as a map, there are 5 inputs, and 5 outputs.
In Python, inputs are called keys, and outputs are called values. Notice how the values have a variety of data types in this dictionary: an integer, three strings… and a tuple of floats.
Python is flexible: you can use all kinds of data types for both keys and values. You are free to mix and match data to suit your needs. If you use the ‘type’ function, you will see ‘post’ is an instance of the ‘dict’ class. This suggests we can use the ‘dict’ constructor to create a dictionary, and this suggestion is correct. Reminder – we are using Python version 3 in this video. Let’s create another Friendface post using the ‘dict’ constructor.
This time, we will only provide a few pieces of data… You can see this made a dictionary. We add additional pieces of data by using brackets. The key name goes inside the brackets, and you use the equals sign to assign the value. Notice that in the constructor, you did not have to put quotes around the key name, but when you add new data using brackets, you DO use quotes. If you print the dictionary, you will see all the data is there inside braces. Just as you use brackets to store new data in a dictionary, you use brackets to access data as well.
Example: to see the message from the first post, use the key name ‘message’ inside brackets. But do not be careless. Let’s see what happens if you try to access data that is not in the dictionary.
When we created ‘post2’, we did not assign a location. If we try to access this value, we get a Key Error. How do we avoid such catastrophes? Simple. One way is to use the ‘in’ operator to first check if a key is in the dictionary. Another way is to try and retrieve the value, but handle the possibility of a KeyError.
The Python Try Except Statement
To do this, type the “try” command followed by a colon. Next, attempt to print the location. If the dictionary does not have a ‘location’ key, it will raise a KeyError. We handle this case by creating an “except” block.
Type “except” and the possible errors you would like to handle. Here, we want to handle the KeyError. If this occurs, the following code block will execute. It works…
There is another way to access data in a dictionary and handle the possibility it does not have a certain key.
First, display the directory for the ‘post2’ dictionary. Here we see a list of methods available to us. We will explore the ‘get’ method. To see what this does, use the help function.
The Get Method
The ‘get’ method lets you try and get the value for a specific key. If the dictionary does not contain data for that key, you can specify a default value. We will use this method to get the ‘location’ from post2. If this post does not have a location, let’s return None.
If you print the value, you see the method did return ‘None.’ Turn your attention back to the original post. A common task is to iterate over all the key/value pairs in a dictionary.
A straightforward way to do this is to loop over all the keys, then get the value for each key. The “keys” method gives us an object we can loop over that contains all the keys for the dictionary. If you are using Python version 2, the output may look different.
This is because we are using Python 3, and in version 3, the print function became more powerful. The order of the data may be different for you. Do not panic.
Python Dictionaries are not ordered data
Dictionaries are not ordered data. As long as you see all the data, everything is under control. Another way to iterate over all the key/value pairs in a dictionary is to use the “items” method.
This will give you both the key and the value in each step of the iteration. There are a variety of methods for removing data from a dictionary. The “pop” and “popitem” methods allow you to remove a single item from a dictionary, while the “clear” method will remove all data.
After you complete this article, be sure to experiment with my course’s exercice files. oh, you’re not enrolled in the course, no problem: Use astateofdata.com special readers’ coupon “ASTATEOFDATA” and get a huge discount!