Python dictionary syntax, need help
Andy Jewell
andy at wild-flower.co.uk
Fri Jul 18 16:58:13 EDT 2003
On Friday 18 Jul 2003 8:42 pm, Crew Reynolds wrote:
> I want to create a dictionary of note on/off timings and access it by
> the name of the object. The following code works for one row.
>
> a = "Hammer1"
> b = [5,45,45,45,45,50,55,57,59,61,60,59]
>
> notes = {a:b}
> print notes["Hammer1"][3]
>
> >>> 45
>
> The problem is, I want to load the data from a file to populate
> variables a and b and build a dictionary for "Hammer1" thru
> "Hammer10". That way, I can stick the name of the object in the array
> index and receive a list of note timings that I can index with an
> ordinal as in the above example.
>
> This is straight Python syntax but I'm hoping someone has done this or
> understands the syntax better than I.
>
> Thanks! Alternative solutions to this concept would be greatly
> appreciated.
sorry, forgot the file bit...
say notesfile.txt has the following structure:
hammer1, 5, 45, 45 45, 45, 50, 55, 57, 59, 61, 60, 59
hammer2, 25, 245, 245, 245, 245, 250, 255, 257, 259, 261, 260, 259
hammer3, 35, 345, 345, 345, 345, 350, 355, 357, 359, 361, 360, 359
hammer4, 45, 445, 445, 445, 445, 450, 455, 457, 459, 461, 460, 459
then we'd need to do something like:
notes={} # and empty dict
notesfile=file("notes.txt") # open the file
for line in notesfile.readlines(): # iterate through its lines
words=line.split(",") # split the line up at every ","
hammer=words[0] # remember the hammer name
for n in words[1:]: # go through the remaining words
try: # We know this could go wrong if the file contains garbage
notes[hammer]=int(n) # try to convert the string to a number
except ValueError: # if the conversion went wrong...
print "Expected number, got:",n # warn the user
notesfile.close() #close the file
hth
-andyj
More information about the Python-list
mailing list