Creating dynamically named lists/dictionaries

John Roth johnroth at
Thu Apr 24 02:23:13 CEST 2003

"Rogue 9" <rogue9 at> wrote in message
news:ydFpa.15$IO5.10324 at
> Hi all,
> I'm new to both programming and Python in particular and have run in
to a
> snag while trying to write my own program.I have looked through books
> the web but haven't as yet found an answer so I though I might try a
> here to see if anyone could point me in the right direction.
> Okay my program is for analysing a Lottery Draw results text file I
> pre-formatted so that each line contains 7 comma separated values
> number and six values representing the numbers drawn in numerically
> ascending order.
> I've sussed out how to open the file read in the lines and I have
> the strings first by the '\n' newline symbol and then I have split it
> again by ','.I've also turned the values back into integers as they
> strings.Now what I've ended up with is a list containing one draw
> for each week (768 at the last count)as individual items in that list
> list =[[767,11,22,33,44,45,46]......[1,20,33,41,45,46,47]]
> What I really want is a list or dictionary for each individual weeks
> result but I can't seem to work out how to dynamically create a list
> dict with a unique name for each week.

You've already got a list for each week. Since I don't know where you're
going with this (that is, I don't know what you mean by "analyze") I
can't give you more specific answers.

So I'm going to assume that what you want is to be able to find the
results by week number. The following (untested) code should give
you an idea.

biglist.sort() # turn the list around so week 1 is at the front.

aWeek = biglist[week-1][1:] # gives you a list of the six result numbers
for the week.

> The results file will grow and I
> don't fancy creating 768+ lines of code just to instantiate a list or
> dict.At first I tried looping a variable equal to the length of the
> as in:
> x=len(filelength)
> 'draw'+str(x)=[drawresult]
> I thought this would dynamically make a whole bunch of lists such as
> draw1,draw2 etc. but all I got was errors.

Unfortunately, you can't do that. There is a way to add names to
a namespace in Python, but it's not what you want. If you want to create
a name for each list, you need a dict. The following (untested) code
build a dict with a name for each week of the lottery, and with the six
numbers as a list.

weekDict = {} # create a dictionary
for weeksNumbers in biglist: # biglist is the list you built on your
    weekDict["draw" + str(weeksNumbers[0])] = weeksNumbers[1:]  # notice
the way it slices the week!

The keys in weekDict will now be "draw1", "draw2" and so forth,
assuming your input list is the one you mentioned before.

> I hope I have explained my 'problem' sufficiently for someone to help
> to at least point me in the right direction to work towards a
> Yours hopefully,
> Rogue9

John Roth

More information about the Python-list mailing list