how to sort a hash list without generating a new object?
Chris Rebert
clp2 at rebertia.com
Tue Aug 2 20:53:26 EDT 2011
On Tue, Aug 2, 2011 at 11:02 AM, smith jack <thinke365 at gmail.com> wrote:
> the source code is as follows
>
> x={}
> x['a'] = 11
> x['c'] = 19
> x['b'] = 13
> print x
>
> tmp = sorted(x.items(), key = lambda x:x[0]) # increase order by
> default, if i want to have a descending order, what should i do?
Pass reverse=True. Read the find documentation for sorted().
tmp = sorted(x.items(), key=lambda x:x[0], reverse=True)
> # after sorted is called, a list will be generated, and the hash list
It's not a hash list (http://en.wikipedia.org/wiki/Hash_list ), it's a
hash table. In Python, we call them dictionaries or dicts.
> x is not changed at all, how to convert x to a sorted hash list
> without generating a new object?
There is no such thing as a sorted hash table (unless you're using an
exotic variant).
Why do you care whether it generates a new object or not?
If you /really/ need a sorted mapping datatype, google for
"sorteddict" (which is quite distinct from OrderedDict).
Or look for a binary search tree or skip list implementation of some
sort; but these aren't commonly used in Python, so it may be hard to
find a good one.
Cheers,
Chris
--
http://rebertia.com
More information about the Python-list
mailing list