[Tutor] Saving and loading data to/from files

Roeland Rengelink r.b.rigilink@chello.nl
Mon, 04 Jun 2001 08:40:39 +0200


Hi Daryl,

Daryl G wrote:
> 
> Ok, I figured out the dictionary problem
> Change the print statement
> for record in NameInfo:
> 
>     print "%-15.15s %-15.15s %s" % (record['first'], record['last'],
> record['phone'])
> 
> now I don't get that error, however I am having difficulty in figuring out
> how to add data to the dictionary.
> This seems to be a sequence directory because of the brackets, correct? Plus
> in some of my attempts I get a TypeError loop non-sequence
> Accessing the values inside is different then a non-sequence directionary.
> Any insight?
> 

NameInfo is a list (sequence). Each element in this list is a
dictionary.

The trick is to know when you are dealing with the list, and when you're
dealing with an item (a dictionary in this case) in the list. Just some
examples to help you on your way:

Here a two-element list of dictionaries is build

NameInfo = [
    {'first': 'Guido', 'last': 'van Rossum', 'phone': '703-555-1234'},
    {'first': 'Eric', 'last': 'Idle', 'phone': '212-555-5346'}]

You can access a list-element by indexing with an integer, i.e the first
element with:

print "%(first)-15.15s %(last)-15.15s %s" % NameInfo[0]
Guido      van Rossum    703-555-1234

(Maybe you're surprised that the first item in a list has index 0. Think
of it as an offset)

You can add a new element using something like:

NameInfo.append({'first':'Basil', 'last':'Fawlty',
'phone':'111-222-33333'}

You can change an element by replacing it with a new dictionary  

NameInfo[0] = {'first':'Tim', 'last':'Peters', 'phone':'333-111-22222'}

You can also address items inside each dictionary, for example

print NameInfo[1]['first']
Eric

(i.e. get the second item in the list and from that item het the value
of 'first') 

Use that to add some info to a dict

NameInfo[2]['birth'] = '01 Apr 1933'   # Date of birth for Basil Fawlty


The summary:

Lists are indexed with integers.
Dictionaries are indexed with a key, which can be pretty much anything

List items are added using the_list.append(item)
Dict items are changed/added using the_dict[key] = value

if you have a list of dicts, you can access an item in a dict with

value = alist[index][key]

which is pretty much equivalent to

record = alist[index]
value = record[key]


Hope this helps,

Roeland Rengelink
-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"