dreamsys software

Python Scripting Tutorial

TOC | Introduction | Variables | If/Else | OptionParser | Looping | Functions | Classes | Strings | Lists & Maps | Shell

Lists & Maps

Under Development...

When your scripts start getting more complex, you will find that you need to use data structures such as lists and maps (i.e. hashtables, hashmaps, dictionaries, etc). First we will cover lists, they are very simple to use in python.

Let's enhance our previous script on classes to now store a list of users.

#!/usr/bin/env python
import sys

#User class
class User:
    name = ""
    age = 0
    height = 0
    weight = 0
    def save(self, f):
        f.write(self.name + '\n')
        f.write(str(self.age) + '\n')
        f.write(str(self.height) + '\n')
        f.write(str(self.weight) + '\n')
    def loadFromFile(self, f):
    	self.name = f.readline().rstrip()
    	self.age = int(f.readline())
    	self.height = float(f.readline())
    	self.weight = int(f.readline())
    def loadFromInput(self):
        self.name = raw_input('Enter User Name (Q to exit): ')
        if self.name == 'Q':
        self.age = int(raw_input('Enter Age: '))
        self.height = float(raw_input('Enter Height (in feet): '))
        self.weight = int(raw_input('Enter Weight: '))

    def display(self):
        print ''
        print 'User Information:'
        print 'User Name  :', self.name
        print 'User Age   :', self.age
        print 'User Height:', self.height
        print 'User Weight:', self.weight
#main program code
users = []

def createUsers():
	while 1:
	   u = User()
	   if u.name == 'Q':
def saveUsers():
	f = open('users.info', 'w')
	f.write(str(len(users)) + '\n')
	for u in users:
def readUsers():
	f = open('users.info', 'r')
	num = int(f.readline())
	for i in range(num):
		u = User()
def displayUsers():
	for u in users:
if len(sys.argv) > 1 and sys.argv[1] == 'READ':

Again the class object is created, this time it adds another parameter to save() and loadFromFile() to take the file object as a parameter instead of opening it in the function each time. The idea of this script is that it will loop while asking for you to enter user info until you enter the name as "Q", then it will quit and save the list. Again if you give the parameter "READ" to the script, it will read the data from a file.

Under the "#main program code" comment, we first create a list with the variable name "users". This is the list where we will keep the users added or read. Next we define a function to create users, this will loop until the name is Q and then break from the while loop. After each user is loaded it will call the append method to add the user to the list.

Next the saveUsers() function will open a save file, write the number of users in the list, then save each user to the file. The readUsers() function works much the same, it opens the file, reads the number of entries in the file from the first line, then reads each user from the file and adds it to the users list. The display() method loops through all users and calls the display() method.

Let's run this once to create some data and then again to read the data:

$ ./userTest.py
Enter User Name (Q to exit): User1
Enter Age: 1
Enter Height (in feet): 2
Enter Weight: 3
Enter User Name (Q to exit): User2
Enter Age: 4
Enter Height (in feet): 5
Enter Weight: 6
Enter User Name (Q to exit): User3
Enter Age: 7
Enter Height (in feet): 8
Enter Weight: 9
Enter User Name (Q to exit): Q

User Information:
User Name  : User1
User Age   : 1
User Height: 2.0
User Weight: 3

User Information:
User Name  : User2
User Age   : 4
User Height: 5.0
User Weight: 6

User Information:
User Name  : User3
User Age   : 7
User Height: 8.0
User Weight: 9
$ ./userTest.py READ

User Information:
User Name  : User1
User Age   : 1
User Height: 2.0
User Weight: 3

User Information:
User Name  : User2
User Age   : 4
User Height: 5.0
User Weight: 6

User Information:
User Name  : User3
User Age   : 7
User Height: 8.0
User Weight: 9

The next data structure we will cover is the map, which is generally referred to as a dictionary in python. This type of data structure is where you map one variable to another. For instance, we could have a "properties" map, where we will set properties and then retrieve them when needed.

For this simple example we will create a properties map and use it to store properties for a URL that we will call and print the contents of.

#!/usr/bin/env python
import urllib

properties = {}

properties['protocol'] = 'http'
properties['host'] = 'www.google.com'
properties['port'] = '80'
properties['path'] = '/trends/'

#the properties in this map represent the URL:

url = properties['protocol'] + '://' + \
      properties['host'] + ':' + \
      properties['port'] + \
print 'Reading URL', url

response = urllib.urlopen(url)

print response.read()

Here we create a map named properties by initializing the variable with {}. We use a string for the key for the map, the following keys are used: 'protocol', 'host', 'port', 'path'. They are given a value so when we lookup the keys the values are returned.

The map is very flexible and this is just a simple illustration of how to use one. In the next section we will cover how to integrate with your unix shell.

Prev (Strings) | Next (Shell)