list/tuple to dict...

Pierre Fortin pfortin at pfortin.com
Thu Sep 16 20:46:57 EDT 2004


On 16 Sep 2004 19:15:42 GMT Bengt wrote:

> 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.

Right!  


> 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))

Would there be a problem with %(key[,len[,prec]]) for the general case?
Notwithstanding the fact that len and prec are positional in my example...
:^)  I'd prefer keeping everything together somehoe, rather than a new
Perl-like 'wart'... but, I'd be pleased to see your attribute-name idea go
forward either way...

You don't mention how %** gets its values though...  typically, I would
use this for row upon row (column widths)...

> 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

Thanks,
Pierre



More information about the Python-list mailing list