Top  | Previous | Next

Sequences and Dictionaries

Python offers a variety of sequence types. We've already seen one - the List. There are other kinds of sequences, most notably tuples and strings. There is also the dictionary type, which contains a list of key-value pairs.

Lists

Lists are a very handy kind of sequence. They can hold any number of items, can be resized on the fly. After creating a list using the square bracket notation, there are a number of functions that you can call on the list. Some common list functions are listed here. Visit http://docs.python.org/tutorial/datastructures.html#more-on-lists for a complete list.

append(x) - takes a single argument, which will be appended to the end of the list.
insert(i,x) - inserts an item x at index i
remove(x) - will remove the given item from the list.
index(x) - returns the index of the value x. Throws an error if the list doesn't contain the item. Use the in operator to check if an item is contained in a sequence.
sort() - sorts the items in the list.

 

myList = ['a''b''c''d']

print myList # --> [a, b, c, d]

 

myList.append("Q")

print myList # --> [a, b, c, d, Q]

 

myList.insert(1"Z")

print myList # --> [a, Z, b, c, d, Q]

 

myList.remove("c")

print myList # --> [a, Z, b, d, Q]

 

print myList[2# --> b

print myLIst.index("b"# --> 2

 

if 'Z' in myList:

   print 'Z is in the list'

 

if 'c' not in myList:

   print 'c was removed from the list'

Tuples

A tuple is similar to a list, but you use parenthesis instead of square brackets to define one. The major difference between a tuple and a list is that tuple's are immutable. That is, once created, they cannot be altered. Tuples are very useful for passing multiple things to and from functions. For example, you could pass a point to a function using a tuple like so:

 

def printPoint(point):

   print "x = ", point[0]

   print "y = ", point[1]

 

printPoint((28,89))

 

This can also be handy for returning multiple values from a function. For example, if you had a mouse event, you could write a function that found the component's center point, and return that point as a tuple. You could then use unpacking assignment to extract the values into separate values.

 

def findCenter(event):

   w = event.source.width

   h = event.source.height

   return (w/2, h/2)

 

# point will be a tuple

point = findCenter(event)

 

# x and y will be numbers, using unpacking assignment

x,y = findCenter(event)

 

Dictionaries

A dictionary is a very useful type that holds a set of key-value pairs. You may have used these in other languages and know them as hashmaps, maps, associative memories or associative arrays. Dictionaries are not ordered sequences - you reference any item via its key value. The keys can be numbers, strings, or tuples of these types. Any given key may only appear once in a dictionary. Trying to set another value for that key will overwrite any previous value for that key.

 

Dictionaries are created using braces ({}).  Key-value pairs are separated by commas, and the keys are separated from the values with a colon. You can use the .keys() function to have a set of the keys. For example:

myDict = {'Bob'89.9'Joe'188.72'Sally'21.44}

 

print myDict['Bob'# --> 89.9

 

myDict['Amir']=45.89 # Adds a key for 'Amir'

 

names = myDict.keys()

names.sort()

print names # --> ['Amir', 'Bob', 'Joe', 'Sally']

 

You can loop through dictionaries using a for loop. You can use the keys() to loop through the dictionary, and then use the key values to look up the value. For example:

for name in myDict.keys():

   print name, myDict[name]