problem of converting a list to dict

John Machin sjmachin at lexicon.net
Wed Jan 9 17:13:43 EST 2008


On Jan 10, 7:34 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att.... at python.org [mailto:python-
> > list-bounces+jr9445=att.... at python.org] On Behalf Of John Machin
> > Sent: Wednesday, January 09, 2008 3:02 PM
> > To: python-l... at python.org
> > Subject: Re: problem of converting a list to dict
>
> > On Jan 10, 6:52 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
>
> > > A bigger hint:
> > >         a=i.split('=')
> > >         print "'%s' splits into " % (i), a
>
> > consider:
> > (1) using %r instead of '%s'
>
>         Eh, personal preference depending on how sure you are of the
> data's type.

For a start, newbies should not assume that they know anything.
Secondly, even if 100% sure that the object is a string object, using
%r instead of '%s' greatly reduces the chance of confusion caused by
content including tabs, newlines, apostrophes, non-ASCII characters,
etc especially when there are e-mail and news clients adding noise to
the channel.

>
> > (2) omitting the redundant space after 'into'
>
>         Some of us coming in from other languages and still aren't used
> to the comma adding an unwanted space after everything.  I've been
> tempted to root around in Python's source code to fix the problem.

There are situations when the space is exactly what is wanted. In
other situations where you need precise control, use file.write and %
formatting. Here's a quick "macro" for retrofreaks:

>>> def fprintf(stream, format, *varargs):
...    stream.write(format % varargs)
...
>>> import sys
>>> fprintf(sys.stdout, "strg:%s int:%d\n", 'foo', 42)
strg:foo int:42
>>>


>
> > (3) losing the redundant () around i
>
>         For me, the () is there for readability.  Python's sprintf
> syntax is odd to begin with, and something like
>                 print "'%s' splits into " % i, a, b, c
>         means either
>                 1) you really do want to append b and c after the
> sprintf, or
>                         print "'%s' splits into " % (a), b, c
>                 2) that the formatting string is missing a few things
>                         print "'%s' splits into " % (a, b, c)  ## Ooops!
> forgot to change it to "%s %5.2d %6.3f"
>

For readability, consider print ("'%s' splits into " % i), a, b, c




More information about the Python-list mailing list