list/tuple to dict...

Bengt Richter bokr at oz.net
Thu Sep 16 15:15:42 EDT 2004


On Thu, 16 Sep 2004 10:16:28 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>Pierre Fortin <pfortin at pfortin.com> wrote:
>   ...
>> 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]
>
>You can implement this exact functionality (not worth it for os.stat, of
>course, which already does return a pseudotuple with named items) in a
>probably better way...:
>
[...]

Perhaps pseudo-tuples that support attribute-name access to elements could
have a __getitem__ that would accept integers in the index way, and strings
as a mapping-like alternative to attribute accesses of the same name.

That way
    '%(st_size)s' % os.stat(filename)
would work.

And if str.__mod__ were modified to have a %** format to establish the corresponding
argument as the effective mapping for string keys yet worked normally from the tuple
for unnamed arguments, then you could write

    '%**%(st_size) is the size of file %r' % (os.stat(filename), filename)

or putting the mapping object in the middle works too, so long as it's before named stuff:

    'File %r is %**%(st_size) long. (full path %r)' % (
        filename, os.stat(filename), os.path.abspath(filename))

you could even entertain multiple mapping objects by specifying %** as you needed new ones.
I think this could be made backwards compatible, since without %** mapping arguments would
either get used or get repr'd, depending, as now.

Regards,
Bengt Richter



More information about the Python-list mailing list