list/tuple to dict...

Peter Otten __peter__ at web.de
Thu Sep 16 03:24:16 EDT 2004


Pierre Fortin wrote:

>> > dict(zip(["mode,inode,dev,nlink,uid,gid,size,atime,mtime,ctime"],
>> > os.stat("%s" % path)))
> 
> What does zip() have to do with this situation...?

It combines the items in the names list with the os.stat() result tuple to a
list of (name, value) pairs that are then used to initialize the
dictionary. For example:

>>> name_value_pairs = zip(["name1", "name2", "nameN"], ["va11", "val2",
"valN"])
>>> name_value_pairs
[('name1', 'va11'), ('name2', 'val2'), ('nameN', 'valN')]
>>> dict(name_value_pairs)
{'nameN': 'valN', 'name2': 'val2', 'name1': 'va11'}


>> Why build the dictionary at all.  Use the named attributes provided by
>> os.stat:
>> 
>>        mode = os.stat(f).st_mode
>> 
>> That should meet the original readability goals.
> 
> That'll teach me to use examples that already have named attributes... :^)
> I'm looking to do this generically -- ignore the few that do have named
> attributes; there are plenty without that I'd like to address...
> 
> The goal is to use the dict in string mapping keys as indicated in my
> original post.

You can still do that while relying on the existing names:

>>> class ObjectAsDictAdapter:
...     def __init__(self, obj):
...             self.obj = obj
...     def __getitem__(self, key):
...             return getattr(self.obj, key)
...
>>> import os
>>> st = os.stat("tmp.py")
>>> "%(st_mtime)s %(st_size)s" % ObjectAsDictAdapter(st)
'1095318348 2'
>>>

You can easily add an analogous 

def __setitem__(self, key, value):
    setattr(self.obj, key, value)

but it won't work in the above example as the stat tuple is immutable.
If you need other attributes (like filename in your original post) you can
solve that with Raymond Hettinger's Chainmap

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268

#untested
"%(filename)s %(st_size)s" % Chainmap(ObjectAsDictAdapter(st),
dict(filename=filename))

Peter





More information about the Python-list mailing list