list/tuple to dict...

Pierre Fortin pfortin at pfortin.com
Wed Sep 15 16:39:09 EDT 2004


Hi,

Is the following a reasonable generic approach for converting python
returned tuples/lists into dicts...?  I'm not advocating library functions
also return dicts (I'd probably spend more time looking up the real
names... :)  I'm just looking to make my code more readable and
self-documenting...


--------
class todict:
    """ Converts a list/tuple to a dict:  foo = todict(values,names) """
    def __init__(self,values,names):
        self.d = {}
        for i,name in enumerate(names.split(",")):
            self.d[name.strip()]=values[i]
    def __setitem__(self, name, value):
        self.d[name]=value
    def __getitem__(self, name):
        return self.d[name]

import os

# called this way, I can see what is returned in what order
uname = todict(os.uname(), "sysname, nodename,release,version, machine")

filename = "/etc/passwd"
osstat = todict(os.stat("%s" % filename),
                "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime")
osstat['filename'] = filename

print "You're running %(sysname)s %(release)s on %(nodename)s" % uname
# mtime needs formatting...
print "File '%(filename)s' was last modified %(mtime)s" % osstat
---------
Returns:
You're running Linux 2.6.3-15mdk on gypsy.pfortin.com
File '/etc/passwd' was last modified 1080568025

A number of values are set and not used; though I think it's a small
price to pay for making the results of lists/tuples more readable and
useful...

Over time, I'll probably build a list of functions I use and just
copy/paste the line(s) I need:

~/pytemplates:
osstat = todict(os.stat("%s" % path),
                "mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime")
uname = todict(os.uname(),
               "sysname, nodename,release,version, machine")
etc...

The only part I still don't like is:
osstat['filename'] = filename

Is there a way to rewrite the class to allow for calls which take parms to
include the parms in the resulting dict..?  I'm probably trying to get too
cute here though... :^)        

The newbie who gets to read (maintain?) my code should have an easier
time; at least, that's my intent...  Though Alex will probably consider
this boilerplating...  I think .some. boilerplating is good...   B-]

Other suggestions welcome :^)

Thanks,
Pierre




More information about the Python-list mailing list