[Tutor] Reversed dictionary returned by default

Dave Angel davea at davea.name
Fri Mar 1 21:03:07 CET 2013


On 03/01/2013 02:48 PM, Huperetes wrote:
> I am getting the following for my installation.
>
> Why is this happening, and how do I get it to work properly (returning
> element 0 - n, versus n - 0)?
>
> Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
>>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa",
> "pwd":"secret"}
>>>> ["%s=%s" % (k, v) for k, v in params.items()]
>
> ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim']
>
>>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
>
> 'pwd=secret;database=master;uid=sa;server=mpilgrim'
>
>>>>
>

A dict has by specification no specific ordering.  If you want the data 
sorted, then sort the data after extracting it.  Or use some other type.

 >>>> ["%s=%s" % (k, v) for k, v in sorted(params.items())]

the only ordering guarantee that you get from dict is that if you 
iterate over it twice with no changes to the dict in the meantime, 
you'll get the same ordering.  But what that ordering is, is undefined. 
  It's certainly not the order that things were entered into the dict.


-- 
DaveA


More information about the Tutor mailing list