Python dictionary syntax, need help

Bengt Richter bokr at oz.net
Fri Jul 18 20:00:15 EDT 2003


On 18 Jul 2003 12:42:06 -0700, crewr at daydots.com (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.

If you want to get it from a file, I suggest making the file space-delimited
and just use an (also space delimited unless see[Note 1]) '=' sign between
dict key and associated values. I'll use the names you suggest, but note that
plain integers will also work as "names" (keys) in a dict, and that might be
handier in some cases, depending on how you want to access the dict.

We'll simulate the file with an intialized StringIO instance:

 >>> import StringIO
 >>> infile = StringIO.StringIO("""
 ... Hammer1 = 5 45 45 45 45 50 55 57 59 61 60 59
 ... Hammer2 = 6 46 46 46 46 51 56 58 60 62 61 60
 ... Hammer3 = 8 48 48 48 48 53 58 60 62 64 63 62
 ... """)

Starting out with an empty notes dict
 >>> notes = {}
 >>> for line in infile:
 ...     if not '=' in line: continue # skip blanks etc
 ...     lineitems = line.split()
 ...     name = lineitems[0]
 ...     numberlist = map(int, lineitems[2:])
 ...     notes[name] = numberlist
 ...

That creates the dict:
 >>> notes
 {'Hammer1': [5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59], 'Hammer3': [8, 48, 48, 48, 48, 53,
 58, 60, 62, 64, 63, 62], 'Hammer2': [6, 46, 46, 46, 46, 51, 56, 58, 60, 62, 61, 60]}

Which you can access per your example:
 >>> notes["Hammer1"][3]
 45

And we can show it in a bit more orderly way:
 >>> tosort = notes.items()
 >>> tosort.sort()
 >>> for name, value in tosort: print name, value
 ...
 Hammer1 [5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59]
 Hammer2 [6, 46, 46, 46, 46, 51, 56, 58, 60, 62, 61, 60]
 Hammer3 [8, 48, 48, 48, 48, 53, 58, 60, 62, 64, 63, 62]

After the 

 ...     lineitems = line.split()

statement, I probably should have added

         assert lineitems[1] == '='

or else been more forgiving and split in two stages, e.g.,

         left, right = line.split('=')
         name = left.strip()
         numberlist = map(int, right.split())
HTH         

Regards,
Bengt Richter




More information about the Python-list mailing list