You are on page 1of 13

Working with lists

and dictionaries

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python
Learning objectives
 Distinguish between lists and dictionaries
 Create and modify a Python list
 Initialize a Python dictionary
 Set keys and values for a dictionary
 Manage data using lists and dictionaries

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-2
What you should already know about lists
 Python lists are:
 Ordered collections
 Stored in variables

fcList = ["Delaware", "Vermont", "Maine", "New York"]

 Indexed

 Accessed by position
fc = fcList[0:-1]

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-3
What you can do with lists
 List functions work for numbers and strings
 sort()– Sorts in sequence from low to high

stList = ["Texas", "Maine", "Idaho"]


stList.sort()
print stList
>>> ['Idaho', 'Maine', 'Texas']

 remove()– Removes first occurrence of an item from the list

areaList = [3086, 23349, 3086, 5774, 17558]


areaList.remove(3086)
print areaList
>>> [23349, 3086, 5774, 17558]

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-4
What you can do with lists (cont’d)
 Change the order in the list
 sort(None, None, 1)– Sorts the list in reverse

stList = ["Maine", "Texas", "Idaho"]


stList.sort(None, None, 1)
print stList
>>> ['Texas', 'Maine', ‘Idaho']

 reverse()– Reverses the sequence (does not sort)

areaList = [3086, 23349, 4596, 5774, 17558]


areaList.reverse()
print areaList
>>> [17558, 5774, 4596, 23349, 3086]

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-5
Adding items to a list
 append() stateList = ["Texas"]
stateList.append("Utah")
 Adds a single item print stateList
to end of the list
>>> ['Texas', 'Utah']

 extend()
stateList.extend(["Iowa", "Ohio"])
 Adds multiple items print stateList
to end of the list
>>> ['Texas', 'Utah', 'Iowa', 'Ohio']

 insert() stateList.insert(1, "Indiana")


print stateList
 Inserts an item
at the index value
>>> ['Texas', 'Indiana', 'Utah', 'Iowa', 'Ohio']

A Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-6
Finding number of items in a list
 Determine total number of items
 len()– Returns the length
numItems = len(stateList)
print numItems

>>> 5

 Find the number of occurrences of an item


 count()– Returns the count

streets = ["Main", "First", "Union", "Main", "Ninth", "South"]


print streets.count("Main")

>>> 2

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-7
Python dictionaries
 Dictionaries are: To initialize a
dictionary:
 Unordered collections
newD = {}
 Stored in variables as key : value pairs

 Keys can be strings or numbers

newD = {"x": 1279359, "y": 337975}


print newD
Scrambled
by default
>>> {'y': 337975, 'x': 1279359}

 Access by key
print newD ["x"]
>>> 1279359

A Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-8
What you can do with dictionaries
 Determine number of items numItems = len(myDct)
print numItems
 len()– Returns the length
>>> 4
 Check for existence of a key
 has_key()

# Key : Value
myDct["Brazil"] = "Brasilia"
myDct["Bolivia"] = "La Paz"
myDct["Guyana"] = "Georgetown"
myDct["Suriname"] = "Paramaribo"

keyList = ["Guyana", "Ecuador"] # Read list of values


for inKey in keyList:
if myDct.has_key(inKey):
print inKey + " already exists"
else:
print inKey + " does not exist in dictionary"

A Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-9
Accessing a dictionary sequentially
 Dictionary keys are not stored in a particular order
 Need to know the key to find a value
 Can use a Python list to access keys

Do not rely
on a specific
sequence in
the list of keys!

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-10
Code example: Access a dictionary

sqkmDict = {} # Initialize a dictionary

# Populate the dictionary


sqkmDict["Suriname"] = 143155
sqkmDict["Brazil"] = 84931
sqkmDict["Bolivia"] = 1090564
sqkmDict["Guyana"] = 210336

kList = sqkmDict.keys() # Store the keys in a Python list


kList.sort() # Sort the Python list
for k in kList:
print "Area of " + k + " is " + str(sqkmDict[k]) + " sq km"

>>> Area of Bolivia is 1090564 sq km


>>> Area of Brazil is 84931 sq km
>>> Area of Guyana is 210336 sq km
>>> Area of Suriname is 143155 sq km

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-11
Exercise goals
 Create and update a list
 Count the items in the list
 Assign keys and values to a dictionary
 Determine whether a key already exists

# Free the memory


del dctPt

Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-12
Lesson review
 Compare and contrast lists and dictionaries

List Dictionary

Ordered collection Yes No

Access by index key

How to determine len(nmList) len(myDct)


number of items nmList.count("Main St")

How to initialize nmList = [] myDct = {}

How to add data to nmList.append("Utah") coords = {"x": 1279359}

A Copyright © 2006–2008 ESRI. All rights reserved. Writing Advanced Geoprocessing Scripts Using Python 3-13

You might also like