Learning About Python Dictionaries

Well, though last week wasn’t too productive code-wise, or even Saturday, I cranked out some new things on Sunday afternoon while I attempted to understand Python dictionaries.

Phonebook v1.0.0

Phonebook v1.0.0

My first (knowing) endeavor into the world of dictionaries was Phonebook. I tried my absolute best to do this one without any help from Hetland, but I couldn’t get the output to make sense, and I saw people[name][key] in the example (peopledb[name][key] in my code), and until I saw it I had no idea how to specify just one part of the key. I still am not entirely sure how/why it works — I suppose I need to do some retroactive reading again.

Regardless, here are the fruits of my labours, phonebook.v1-0-0.py:

#!/usr/bin/env python

# phonebook.py v1.0.0
# Phonebook
#
# Changelog:
# v1.0.0 (09/12/2010) - Initial release
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# dictionary database of Alice, Bob, & Cecilia's phone/addr info

peopledb = {
	"Alice": {"phone": "(555) 241-0244", "addr": "123 Happy Street"},
	"Bob": {"phone": "(555) 241-3410", "addr": "456 Cherry Avenue"},
	"Cecilia": {"phone": "(555) 813-5801", "addr": "789 Neverending Circle"}
}

# user interface 😛

print "Phonebook v1.0.0"
print "Copyright 2010 by Benjamin Braithwaite"
print
print "Sample phonebook application"
print
name = raw_input("Name to look up (Alice, Bob, or Cecilia): ")
print
whatinfo = raw_input("Do you want %s\'s phone number (p) or address (a)?: " % (name))
print

# choose output based on what info user requests

if whatinfo == "p": key = "phone"
if whatinfo == "a": key = "addr"

# format depending on info requested

whatformat = {"addr": "address", "phone": "phone number"}

# print output requested if available, else print error message

if name in peopledb: print "%s\'s %s is %s." % (name, whatformat[key], peopledb[name][key])
else: print name + "\'s name is not in the database."
print

# successful exit dialog

raw_input ("Press <enter> to exit.")

You can download phonebook.v1-0-0.py from my Dropbox. I kinda cheated with the if/else stuff by guessing how they might work, and testing until something finally did work, so whether it’s either brilliant or hideous, I won’t know until later. (I’m hoping it’s brilliant. :mrgreen: ) From coding Phonebook, I saw that dictionaries could do string substitution like importing Template could (showcased in Madlibs), but it would require a lot more effort on the programming side beyond a fairly small template size (because you’d have to list in order the substitution information)… or so I thought.

HTML Page Generator v1.0.0

HTML Page Generator v1.0.0

Cleverly using dictionaries and %(foo)s lets you pick specific dictionary keys to insert (foo in this case), then use % to pick which dictionary to read from — similar (or perhaps functionally equivalent) to Template, and neater, too! To see if this was the case, I made HTML Page Generator, which generates a simple HTML page from user input. And here, for your reading pleasure, is htmlpagegenerator.v1-0-0.py:

#!/usr/bin/env python

# htmlpagegenerator.py v1.0.0
# HTML Page Generator
#
# Changelog:
# v1.0.0 (09//2010) - Initial release
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "HTML Page Generator v1.0.0"
print "Copyright 2010 by Benjamin Braithwaite"
print
print "Generate a simple HTML page"
print

# HTML template

htmltemplate = """<html>
<head>
    <title>%(title)s</title>
</head>
<body>
    <h1>%(header1)s</h1>
    <p>%(para)s</p>
</body>
</html>"""

# create and fill dictionary of user's choices

htmldict = {}

htmldict["title"] = raw_input("Title of your page: ")
htmldict["header1"] = raw_input("Header: ")
htmldict["para"] = raw_input("Content: ")

# print user's choices in HTML template

print
print htmltemplate % htmldict
print

# successful exit dialog

raw_input ("Press <enter> to exit.")

You may also download htmlpagegenerator.v1-0-0.py from my Dropbox.

I didn’t study dictionaries very deeply this past week, but what I saw was very intriguing, and I think they will be a great playground for future projects. This week I hope to delve more deeply into Python dictionary capabilities and applications, and perhaps even peek into the wide world of if statements!

UPDATE: Added screenshots.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s