Python dictionary syntax, need help
Andy Jewell
andy at wild-flower.co.uk
Fri Jul 18 16:34:30 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.
So you want something like:
Python 2.2.1 (#1, Dec 4 2002, 23:43:31)
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux-i386
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> notes={"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],
}
>>>#let's play at indexing...
>>> notes["hammer1"]
[5, 45, 45, 45, 45, 50, 55, 57, 59, 61, 60, 59]
>>> notes["hammer2"]
[25, 245, 245, 245, 245, 250, 255, 257, 259, 261, 260, 259]
>>> notes["hammer2"][5]
250
>>> notes["hammer2"][10]
260
>>> notes["hammer4"][11]
459
>>>#what keys did we have?
>>> notes.keys()
['hammer1', 'hammer3', 'hammer2', 'hammer4']
>>>#lets 'process' the dict (enumerate the keys)
>>> for hammer in notes.keys():
print "hammer:",hammer,
for note in notes[hammer]:
print note,
print
hammer: hammer1 5 45 45 45 45 50 55 57 59 61 60 59
hammer: hammer3 35 345 345 345 345 350 355 357 359 361 360 359
hammer: hammer2 25 245 245 245 245 250 255 257 259 261 260 259
hammer: hammer4 45 445 445 445 445 450 455 457 459 461 460 459
>>>#Ah! the hammers are in the wrong order because dictionaries don't
>>>#preserve sequences. We just need to sort the keys...
>>> hammers=notes.keys() #get the keys into a list
>>> hammers.sort()
>>> for hammer in hammers:
print "hammer:",hammer,
for note in notes[hammer]:
print note,
print
hammer: hammer1 5 45 45 45 45 50 55 57 59 61 60 59
hammer: hammer2 25 245 245 245 245 250 255 257 259 261 260 259
hammer: hammer3 35 345 345 345 345 350 355 357 359 361 360 359
hammer: hammer4 45 445 445 445 445 450 455 457 459 461 460 459
>>> #that should do it!
hope that helps
-andyj
More information about the Python-list
mailing list