[Tutor] Turn a file into a dictionary

Magnus Lycka magnus@thinkware.se
Sat, 28 Sep 2002 23:53:05 +0200


At 15:06 2002-09-28 -0600, Colin Campbell wrote:
>Hello Python gurus!
>
>I have a file containing a series of records. Each record consists of a 
>username in the first field, then a comma separated list of a variable 
>number of tab names.I optimistically built the file in what I thought 
>would be the form of a dictionary:
>
>{user1:tab3,tab5}
>{User2:tab1,tab2,tab3,tab4,tab5}

A python dictionary would be

d = {user1: (tab3,tab5),
      User2:(tab1,tab2,tab3,tab4,tab5)}

right?

You don't want a separate dictionary with just
one key for each user, do you?

>with the intent of simply writing:
>
>f=open('C:\Other\Prg\ACL.CSV','r')
>dict=f.readlines()

When you read a text file with .readlines(), you get a
list of strings. Nothing else.

I think you understand that text files can contain lots of
things, and Python can't by magic assume that it should
interpret read text as code, even if the text would look like
code. That would certainly cause much more grief than happiness.

What if you write a python programmers editor, and instead
of presenting your code in the editor, it tries to execute
it when you open a file?

For python to interpret a file as code, you typically
use import, but you can for instance read it in like
a string and use the eval() function to evaluate it
as python code. (There is also exec() etc.)

So, if you wrote your file as:

user1: (tab3,tab5),
User2:(tab1,tab2,tab3,tab4,tab5),

you could do:

myFileText = file(filename).read()
d = eval("{ %s }" % myFileText)

and you would get:

d = {user1: (tab3,tab5),
      User2:(tab1,tab2,tab3,tab4,tab5)}

But what happened here? user1, tab3 etc are assumed
to be variable names. So for this to work, there must
already be variable with these names in your code, or
you will get

NameError: name 'user1' is not defined

I would certainly not recommend using this strategy.

Maybe the dict you wanted was really?

d = {'user1': ('tab3','tab5'),
      'User2':('tab1','tab2','tab3','tab4','tab5')}

A dictionary with a string as key, and a tuple of
strings as value?

In that case I'd recommend that you simply write your
file as:

user1, tab3, tab5
User2, tab1, tab2, tab3, tab4, tab5

And do:

d = {}
for line in file(filename, 'rt'):
     items = [x.strip() for x in line.split(',')]
     d[items[0]] = tuple(items[1:])

A similar situation would be to read a unix passwd file.
There items are separated by : and arbitrary whitespace
is not allowed if memory serves me right. Then it would
be:

users = {}
for line in file('/etc/passwd', 'rt'):
     items = line.rstrip().split(':')
     users[items[0]] = tuple(items[1:])




-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se