[Tutor] Reversed dictionary returned by default
Prasad, Ramit
ramit.prasad at jpmorgan.com
Fri Mar 1 21:35:39 CET 2013
Dave Angel wrote:
> 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.
>
>
In Python 2.7+, OP can also try using an OrderedDict[0].
"When iterating over an ordered dictionary, the items are returned in the
order their keys were first added."
Note, that updating a key will NOT change the order, so you must remove
the key/value pair and then re-add it to change the ordering.
Ramit
[0] http://docs.python.org/2/library/collections.html#collections.OrderedDict
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list