Creating dynamically named lists/dictionaries

Bengt Richter bokr at oz.net
Wed Apr 23 23:42:27 EDT 2003


On Thu, 24 Apr 2003 00:22:18 +0100, "Rogue 9" <rogue9 at ntlworld.com> wrote:

>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 and
>the web but haven't as yet found an answer so I though I might try a post
>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 have
>pre-formatted so that each line contains 7 comma separated values (Draw
>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 split
>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 were
>strings.Now what I've ended up with is a list containing one draw result
>for each week (768 at the last count)as individual items in that list e.g
>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 or
>dict with a unique name for each 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 file
>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.
>	I hope I have explained my 'problem' sufficiently for someone to help or
>to at least point me in the right direction to work towards a solution.
Maybe this will give you some ideas...

====< lottery.txt >=================
1,11,12,13,14,15,16
2,21,22,23,24,25,26
3,31,32,33,34,35,36
4, -- intentionally bad line --
5,xx,52,53,54,55,56 -- also bad
767,11,22,33,44,45,46
====================================
====< lottery.py >==================
def test(filepath):
    drawdict = {}
    for drawline in file(filepath):
        nums = map(str.strip, drawline.split(','))
        if nums == ['']: continue # skip blank lines silently
        try:
            nums = map(int, nums)
            if len(nums) != 7: raise ValueError
        except ValueError:
            print 'Bad data line: %s' % `drawline`
        else:
            drawdict['draw%s' % nums[0]] = nums[1:]
    return drawdict

if __name__ == '__main__':
    import sys
    if len(sys.argv)>1:
        dd = test(sys.argv[1])
        for k,v in dd.items():
            print '%10s: %s' % (k, v)
        print 'Just press Enter to exit ;-)'
        while 1:
            key = raw_input('Enter draw id in form "drawN": ')
            if not key: break
            val = dd.get(key, '(None stored in dict)')
            print '    Result for drawing "%s" is %s' % (key, val)
    else:
        print 'Usage: [python] lottery.py filepath'
 ====================================

 [20:37] C:\pywk\clp>python lottery.py
 Usage: [python] lottery.py filepath

 [20:37] C:\pywk\clp>python lottery.py lottery.txt
 Bad data line: '4, -- intentionally bad line --\n'
 Bad data line: '5,xx,52,53,54,55,56 -- also bad\n'
    draw767: [11, 22, 33, 44, 45, 46]
      draw3: [31, 32, 33, 34, 35, 36]
      draw2: [21, 22, 23, 24, 25, 26]
      draw1: [11, 12, 13, 14, 15, 16]
 Just press Enter to exit ;-)
 Enter draw id in form "drawN": xxx
     Result for drawing "xxx" is (None stored in dict)
 Enter draw id in form "drawN": draw2
     Result for drawing "draw2" is [21, 22, 23, 24, 25, 26]
 Enter draw id in form "drawN": draw767
     Result for drawing "draw767" is [11, 22, 33, 44, 45, 46]
 Enter draw id in form "drawN":

 [20:37] C:\pywk\clp>python
 Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import lottery
 >>> d = lottery.test('lottery.txt')
 Bad data line: '4, -- intentionally bad line --\n'
 Bad data line: '5,xx,52,53,54,55,56 -- also bad\n'
 >>> d
 {'draw767': [11, 22, 33, 44, 45, 46], 'draw3': [31, 32, 33, 34, 35, 36], 'draw2': [21, 22, 23, 2
 4, 25, 26], 'draw1': [11, 12, 13, 14, 15, 16]}
 >>> d.keys()
 ['draw767', 'draw3', 'draw2', 'draw1']

Hm, that bad data output might not be the best way to handle the errors. And you might
want to move stuff into test to do more of interest there, or write another routine that
uses test (and give it a better name ;-) Whatever, have fun.

Regards,
Bengt Richter




More information about the Python-list mailing list