[Zope] building a sorted dictionary
p.t.
p.training@tin.it
Fri, 17 May 2002 02:15:24 +0200
Yes, thanks to the list-hints, now I know a bit better.
I do not undestand the "logical reason" why a map or dictionary should
necessarely be random (fortunatly this is not true for printed
doctionaries!), but this is how it works in Python.
Now, my real problem is not directly connected with sorting the mapping
keys, but having an access to the dictionary keys sorted according an
attribute value in a structure like:
aDict = {key_m:{attr_a:xx, attr_s:'K', ...}, key_b:{attr_a:yy, attr_s:'D',
...}, ...}
where the sorting item is attr_s.
So, I do need to get key_b value before key_m value because attr_s is
'D' in key_b and 'K' in key_m.
My attempt was to avoid a dynamic sorting on attr_s each time a need a
sequenced access, trying to produce a static and already sorted dictionary.
Now I suppose that to avoid such dynamic sorting I have to extract a
dictionary like:
reverseDict = {5:key_m, 2:key_b, ...}
reverseItems = reverseDict.keys()
reverseItems.sort()
Then to get the attr_a value in the expected sequence:
for item in reverseItems:
attr_a = aDict[ reverseDict[ item] ]['attr_a']
...
Following Andreas's suggestion, I didn't find a better solution looking
around ( python.faqts and ASPN/Python).
Some more hints?
TIA,
p.t.
At 18:27 16/05/2002 -0400, Andreas Jung wrote:
>Python dictionaries are unsorted. I have seen several implementations of
>sorted
>dictionaries flying around on the net. Check google for "python sorted
>dictionary" or so.
>
>-aj
>
>----- Original Message -----
>From: "p.t." <p.training@tin.it>
>To: <zope@zope.org>
>Sent: Thursday, May 16, 2002 17:59
>Subject: [Zope] building a sorted dictionary
>
>
> > Not knowing Python very well, I could'nt manage to find a way to build a
> > dictionary in a predefined sort sequence: any attempt produces a "random"
> > result.
> > Any hint?
> > TIA,
> > p.t.
> >