Python dictionary syntax, need help

Peter Abel p-abel at t-online.de
Sat Jul 19 06:41:36 EDT 2003


crewr at daydots.com (Crew Reynolds) wrote in message news:<56ba0aea.0307181142.7401aa02 at posting.google.com>...
> 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.

>>> # Reading the note_txt from file and splitting it by lines
>>> # by split('\n') and not by realines to avoid '\n' at the end of
line
>>> note_lines=file('notesfile.txt').read().split('\n')
>>> # If the last line had a '\n' at the end you'll get
>>> # an empty list for the last line. We'll get rid of it.
>>> if not len(note_lines[-1].strip()):del note_lines[-1]
... 
>>> # Splitting the lines by comma to get a list for each line
>>> # It's supposed that the first item is the key
>>> note_lists=map(lambda line:line.split(','),note_lines)
>>> # Making a dict from tuples(key,list), where the key is the
>>> # 1st item of note_list[i] and list is the rest of note_list[i]
>>> notes=dict( map(lambda l: (l[0],l[1:]) , note_lists) )
>>> # The result:
>>> for (k,v) in notes.items():
... 	print '%-10s: %s'%(k,v)
... 
hammer1   : [' 5', ' 45', ' 45', ' 45', ' 45', ' 50', ' 55', ' 57', '
59', ' 61', ' 60', ' 59']
hammer3   : [' 35', ' 345', ' 345', ' 345', ' 345', ' 350', ' 355', '
357', ' 359', ' 361', ' 360', ' 359']
hammer2   : [' 25', ' 245', ' 245', ' 245', ' 245', ' 250', ' 255', '
257', ' 259', ' 261', ' 260', ' 259']
hammer4   : [' 45', ' 445', ' 445', ' 445', ' 445', ' 450', ' 455', '
457', ' 459', ' 461', ' 460', ' 459']
>>> 
Regards Peter




More information about the Python-list mailing list