Python Dictionaries

pythonStickersDictionaries, also called dicts, are Python’s native mapping data type. Dictionaries allow rapid data lookup and enumerations; both very useful in using Python for programming and data analysis.

 

Dictionaries are unordered and are defined by key:value pairs in curly brackets { } and typcially hold data that are related such as information contained in a user profile. In our example, since I work with geologic data, I will use some hypothetical exploration drillhole information.

A dictionary looks like this:

In [62]:

 Keys & Values

For your reference DDH2018_001 is a drillhole ID and the keys are northing, easting, and elevation (geographical coordinates), depth,Surveyed, and surveyor.

The values in this example are 1506890, 4569873, 6456, 1465, True, and 'IDS'. Values can be any datatype. In this example there are integer, Boolean, and string data.

Printing

 Printing a dicitonay is done the same wall as any printing call in Python 3:
In [63]:
 {‘northing’: 1506890, ‘easting’: 4569873, ‘elevation’: 6456, ‘depth’: 1465, ‘surveyed’: True, ‘surveyor’: ‘IDS’}

Accessing Values with Keys

Values in dictionaries are easy to access by calling the key of the data you need. To see just the depth of DDH20018_001 we do the following:

In [64]:
1465

Dictionaries are similar to databases in that it is possible to retrieve data by calling a key, which is acting like record number.

In [65]:
True
IDS

Accessing Dictionary Elements with Methods

It is also possible to use built-in dictionary methods to obtain information about a dictionary:

dict.keys()        – returns all keys
dict.values()    – returns all values
dict.items()      – returns all items in a list of
(key,value) .       – tuple pairs

In [66]:
dict_keys(['northing', 'easting', 'elevation', 'depth', 'surveyed', 'surveyor'])

This returned an iterable list of dict keys.

In [67]:
dict_values([1506890, 4569873, 6456, 1465, True, 'IDS'])

This returned an iterable list of dict values.

In [68]:
dict_items([('northing', 1506890), ('easting', 4569873), ('elevation', 6456), ('depth', 1465), ('surveyed', True), ('surveyor', 'IDS')])

This returned an iterable list of (key,value) pairs.

These methods provide iterable view objects for the dict.keys(), dict.values(), dict.items() classes. This makes it possible to query across dicts to find common values and differences. We will compare DDH2018_001 and DDH2018_002:

 

In [69]:
True True
6456 6502
IDS MineDept
1506890 150000
1465 1503
4569873 4569450

From compairing these two drillholes we can see they have the same keys, or fields, and all fields are contain data. This can be extremely useful when comparing large dictionaries.

Another trick we can do is iterate the view of dict.items from above and incorporte them into a sentence using a for loop. This can be useful when extracting data into a readable format for human consumption.

 

In [70]:
northing is the key for the value 1506890
easting is the key for the value 4569873
elevation is the key for the value 6456
depth is the key for the value 1465
surveyed is the key for the value True
surveyor is the key for the value IDS

Modifying Dictionaries

Since dictionaries are mutable, it is possible to make changes to them by adding, deleting, and changing elements.

To add a value we execute dict[key]=value.

 

In [71]:
{'P1': 'DDH2018_001', 'P2': 'DDH2018_002', 'P3': 'DDH2018_003'}

The dictionary of proposed drillhole IDs has been updated to include P3 : DDH2018_003. Using this same syntax it is possible to change any value in a dictionary. Let’s assume that the survey for DDH2018_002 needs to be removed from the dictionary because the readings were flawed. To show that DDH2018_002 has been removed, we will change the dictionary to show survey:False

 

In [72]:
{'northing': 150000, 'easting': 4569450, 'elevation': 6502, 'depth': 1503, 'surveyed': False, 'surveyor': 'MineDept'}

It also possible to modify dictionaries using the dict.update(). Since the the surveyed value for DDH2018_002 has been changed to Falsewe need to update surveyor to None.

 

In [73]:
{'northing': 150000, 'easting': 4569450, 'elevation': 6502, 'depth': 1503, 'surveyed': False, 'surveyor': 'None'}

We can see that 'surveyor' record has been successfully updated to 'survyeor':'None'.

Deleting Elements from a Dictionary

Deleting elements from a dicitonary is just as easy as adding and updating dictionary elements. To delete a dictionary element we will use del dict[key]. Let’s imagine we discovered all of the elevation data for DDH2018_002 is wrong and we just want to delete until the correct coordinates can be provided. To delete the coordinates we perform the following:

 

In [74]:
{'northing': 150000, 'easting': 4569450, 'elevation': 6502, 'depth': 1503, 'surveyed': False, 'surveyor': 'None'}
{'northing': 150000, 'easting': 4569450, 'depth': 1503, 'surveyed': False, 'surveyor': 'None'}

The command del DDH2018_002['elevation'] has removed the elevation data as demonstrated by the two lists above. We have now learned that all of the information for DDH2018_002 is incorrect so we will clear all values by executing dict.clear().

 

In [75]:
{'northing': 150000, 'easting': 4569450, 'depth': 1503, 'surveyed': False, 'surveyor': 'None'}
{}

As we can see from the empty brackets that were returned when printing DDH2018_002 the information was successfully cleared. Now, since there is not need for DDH2018_002 it can be deleted completely like so:

 

In [76]:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-76-832d004d1908> in <module>()
      1 del DDH2018_002
----> 2 print(DDH2018_002)

NameError: name 'DDH2018_002' is not defined

Since DDH2018_002 was deleted, we receive an error when we try to print it.

Final Thoughts

In this overview we covered some of the most commonly used dictionary functions and methods. There are many more you will pick up as you learn more Python and I will show more advanced dictionary methods in a future post if you would like to come back and learn more. If this has been useful to you, or if you have some good dictionary please leave a comment below or contact me on Twitter.