[Tutor] Dictionary Question
Steven D'Aprano
steve at pearwood.info
Wed Dec 22 13:31:39 CET 2010
Garry Bettle wrote:
> Howdy all,
>
> Hope this message finds everyone well.
>
> I have dictionary of keys and a string of values.
>
> i.e.
>
> 8 Fixtures:
I assume each fixture is a key, e.g. Swin, HGrn, etc.
> Swin 1828 1844 1901 1916 1932 1948 2004 2019 2036 2052 2107 2122
> HGrn 1148 1204 1218 1232 1247 1304 1319 1333 1351
> Newc 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403
> Yarm 1833 1849 1906 1922 1937 1953 2009 2024 2041 2057 2112
> BVue 1418 1437 1457 1517 1538 1558 1618 1637 1657 1717 1733 1747 1804 181
> Hove 1408 1427 1447 1507 1528 1548 1608 1627 1647 1707 1722 1738 1756 181
> Romfd 1930 1946 2003 2019 2035 2053 2109 2125 2141 2157 2213 2230
> Sund 1839 1856 1911 1927 1943 1958 2014 2031 2047 2102 2117
>
> I print that with the following:
>
> f = open(SummaryFile, 'a')
> header = "%d Fixtures, %d Races:\n" % len(FixtureDict.keys())
> print header
>
> f.write(header)
> f.write("\n")
> for fixture, racetimes in FixtureDict.iteritems():
> line = "%s\t%s" % (fixture, " ".join(racetimes))
According to your description, racetimes is already a single string, so
using join on it would be the wrong thing to do:
>>> racetimes = "1839 1856 1911"
>>> " ".join(racetimes)
'1 8 3 9 1 8 5 6 1 9 1 1'
So what is racetimes? Is it a string, or is it a list of strings?
['1839', '1856', '1911']
I'm going to assume the latter. That's the right way to do it.
> print line
> f.write(line + "\n")
> f.write("\n")
> f.close()
>
> What I'd like to is add the number of values to the Header line.
>
> So how would I get i.e.
>
> 8 Fixtures, 93 Races
>
> I tried
>
> header = "%d Fixtures, %d Races:\n" % (len(FixtureDict.keys()),
> len(FixtureDict.values()))
>
> But I get
>
> print header
>>> 8 Fixture, 8 Races
>
> Any ideas?
You need len(racetimes) rather than len(FixtureDict.values()).
Every dict has exactly one value for every key, always, without
exception. That is, len(dict.keys()) == len(dict.values()). In this
case, the values are lists of multiple start times, but each list counts
as one value. You need to count the number of items inside each value,
not the number of values.
In this case, you need to sum the number of races for all the fixtures:
num_races = sum(len(racetimes) for racetimes in FixtureDict.values())
--
Steven
More information about the Tutor
mailing list