Masthead

Python Dictionaries

Introduction

A Python dictionary is like a list but you can have names associated with each of the entries in the list.

Simple Dictionaries

Below is the code to create a simple dictionary with information on one tree.

TheDictionary = {
	"Species": "Sequoia sempervirens",
	"Latitude": 40.509281,
	"Longitude": -123.893549
}
print("The entire dictionary: "+format(TheDictionary))

The code below will access each of the elements of the dictionary in a way that is very similar to lists but with a label for each of the elements.

TheSpecies=TheDictionary["Species"]
TheLatitude=TheDictionary["Latitude"]
TheLongitude=TheDictionary["Longitude"]

print("The species: "+format(TheSpecies))
print("The location: "+format(TheLatitude)+", "+format(TheLongitude))
   

More Complex Dictionaries

The real power of dictionaries is in combining them with arrays. The example below contains multiple entries for trees from the Forest Inventory Analysis (FIA) database.

ArrayOfDictionaryentries=[
    {
        "Species": "Sequoia sempervirens",
        "Latitude": 40.509281,
        "Longitude": -123.893549
    },
    {
        "Species": "Sequoia sempervirens",
        "Latitude": 41.139693,
        "Longitude": -123.975794
    }
]
print("The entire array: "+format(ArrayOfDictionaryentries))

Now, we can iterate through the array to get each dictionary entry and then pull the individual values from the dictionary entry as below.

Index=0
while (Index<len(ArrayOfDictionaryentries)):
	
	TheDictionary=ArrayOfDictionaryentries[Index]
	
	TheSpecies=TheDictionary["Species"];
	TheLatitude=TheDictionary["Latitude"];
	TheLongitude=TheDictionary["Longitude"];
	
	print("The species: "+format(TheSpecies))
	print("The location: "+format(TheLatitude)+", "+format(TheLongitude))
	
	Index+=1 

Additional Resources

W3Schools Tutorial on Python Dictionaries

© Copyright 2018 HSU - All rights reserved.