Using String for new List name

Duncan Booth duncan.booth at invalid.invalid
Mon Sep 28 13:11:48 EDT 2009


Scott <scott.freemire at gmail.com> wrote:

> for X in open("file1"):
>     Do a test.
>     If true:
>         Y = re.split(" ", X)
>         Z = Y[0]          # This is a string, maybe it is "Line42"
>         Z = []              # This doesn't work, I want a new, empty
> list created called Line42 not Z.
> 
> Is there any way to do this?
> 

Use a dictionary. Also use meaningful variable names, don't use regular 
expressions unless you actually get some benefit from using them, and 
always close the file when you've finished with it.

values = {}
with open("file1") as f:
    for line in f:
        fields = line.split(None, 1)
        values[fields[0]] = []



More information about the Python-list mailing list