An introduction to dictionaries
Introduction
programmers love to organise information! Lists and tuples store information in sequences. Dictionaries allow you to organise information in a completely different way, as pairs of values. You can think of a dictionary in the same way as a real dictionary; you look up a word and then you get its definition. Python dictionaries are the same; you look up a key and you get its value.
Here is a dictionary of acroynms used in computing.
You can see that we have used curly brackets to create a dictionary. Each key-value pairing is separated by a colon, and each pair is separated by a comma. You can print out the entire dictionary by giving the name of the dictionary to a print statement. To get a value back, you simply use the key. To get back the meaning of DRAM, for example, you use the key value 'DRAM'. Note that this doesn't work in reverse though. You can't use the value to get back a key. Try it and see!
Dictionaries are organised in pairs and the only way to get back a piece of data is to use the key. There are no position indicators like there are with lists and tuples.
Checking to see if a key exists
You can easily check to see if a key exist before try to use it to get some data back, using the in operator. For example:
Dictionaries are objects and as you know, objects have methods that you can use associated with them. One of the in-built methods that dictionaries have is get. This method has some error handling in, so if you ask for a key that doesn't exist, you can specify a default value to display, like this:
By using this method, you can guarantee getting a value back, either the one in the dictionary or a default value.
Adding a removing key-value pairs
You can add new key-value pairs to a dictionary by stating the dictionary name, the key and the value. You can remove key-value pairs by using the keyword del along with the dictionary name and the key of the key-value pair you want to delete. Here is an example, where we add an entry for ISP and then delete the key-value pair for CPU:
Q1. What kind of brackets do you use for lists, tuples and dictionaries?
Q2. Get the above dictionary working in Python.
Q3. Add code to add the following acromyms:
WWW : World Wide Web
WAN : Wide Area Network
VGA : Video Graphics Array
Check it works.
Q4. Add code to delete the entries for RAM and ROM and then check it works correctly.
Q5. Write code using the in operator to check to see if LAN is in the dictionary.
Q6. Use the get method to get back the values for ALU and WEP. Display a suitable default message if either isn't in the dictionary.
Q7. Find and use three other methods associated with a dictionary object.
Q8. How would you create an empty dictionary called capitals?