Order by value in dictionary

cokofreedom at gmail.com cokofreedom at gmail.com
Wed Oct 17 10:10:27 EDT 2007


On Oct 17, 4:06 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Diez B. Roggisch wrote:
> > Abandoned wrote:
>
> >> Hi..
> >> I have a dictionary like these:
> >> a={'a': '1000', 'b': '18000', 'c':'40', 'd': '600'} ...... 100.000
> >> element
> >> I want to sort this by value and i want to first 100 element..
> >> Result must be:
> >> [b, a, d, c .....] ( first 100 element)
>
> >> I done this using FOR and ITERATOR but it tooks 1 second and this is
> >> very big time to my project.
> >> I want to learn the fastest method..
>
> > That is the fastest method, unless you write your own ordered dict
> > implementation that sorts by value. But that will most probably lose the
> > time when holding up the invariant when inserting key/values into the
> > dictionary.
>
> Actually, I somehow read the FOR and ITERATOR above as something like this:
>
> entries = sorted(a.items(), key=lambda v: v[1])[:100]
>
> The gist of my statement above is nontheless the same: if you want sorted
> results, you need to sort...
>
> Diez

Agreed, and it seems using the inbuilt sorts is the most efficient
way...




More information about the Python-list mailing list