1

I'm trying to sort an ordereddict, but without luck. I tried using the method found at https://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

        for d in results:
            print(d)

        d = OrderedDict(results)

        for key in d:
            print(d[key])

        hi = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

        for key in hi:
            print(hi[key])

this prints out:

('GOOG/CPH_43740', -1.6749609142444124)
('GOOG/CPH_CARL_B', 0.66869383328307086)
('GOOG/CPH_CHR', 0.6270772411141563)
('GOOG/CPH_EGE_B', -0.89015989892984237)
('GOOG/CPH_GEN', 0.46485175444884497)

-1.67496091424
0.668693833283
0.627077241114
-0.89015989893
0.464851754449

-1.67496091424
0.668693833283
0.627077241114
-0.89015989893
0.464851754449

Which is not sorted, by descending order. Am i totally lost here?

smci
  • 32,567
  • 20
  • 113
  • 146
vandelay
  • 1,965
  • 8
  • 35
  • 52
  • 4
    You have explicitly sorted in ascending order of **key**, which is exactly what you got. – jonrsharpe Aug 05 '16 at 19:20
  • This should not have been closed as duplicate. Sorting by value is one thing; retaining that in a new OrderedDict specifying the new insertion order requires declaring a new OrderedDict. (cc: @PadraicCunningham) – smci Dec 11 '16 at 04:13
  • @JacuesdeHooge's answer is right and I want to redirect ["return a dictionary after sorting"](https://stackoverflow.com/questions/41082822/return-a-dictionary-after-sorting) here as canonical. This needs to be reopened as separate question in its own right. – smci Dec 11 '16 at 04:24

1 Answers1

3

Assuming you want to sort on the numbers, which have index 1 rather than 0 inside your tuples:

    for d in results:
        print(d)

    d = OrderedDict(results)

    for key in d:
        print(d[key])

    hi = OrderedDict(sorted(d.items(), key=lambda t: t[1]))

    for key in hi:
        print(hi[key])
Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45