[Tutor] Help with a Dictionary
Alan Gauld
alan.gauld at btinternet.com
Thu Jan 7 17:38:13 CET 2010
"Garry Bettle" <garry.bettle at gmail.com> wrote
> What I'd like to do, is output a transposed-like summary of just the
> Fixture + RaceTime.
> Sund 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351
> Sheff 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403
> As the races are output, I build a dictionary of key=FixtureName and
> value=RaceTimes:
Good start although I'd probably have just built a list rather than
building a long string.
> if FixtureName not in FixtureList:
> FixtureList[FixtureName] = cRaceTime
> else:
> FixtureList[FixtureName]+= " " + cRaceTime
if FixtureName not in FixtureList:
FixtureList[FixtureName] = [cRaceTime]
else:
FixtureList[FixtureName].append(cRaceTime)
> And then, when I want the summary to be printed:
>
> for fixture in FixtureList:
> print fixture.ljust(6), FixtureList[fixture]
for fixture, fixtures in FixtureList:.iteritems()
print "%s\t%s" % (fixture, " ".join(fixtures))
> It works, but have I done it the "python" way?
> Can't I unpack both the key and value from FixtureList?
iteritems() as above.
> Another thing I'd like to change is the ljust(). I believe it's
> depreciated later in 3.0+, so I should really find an alternative.
Using a format string you can control justification and total space,
however I just added a tab character.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list