vandelay vandelay - 3 months ago 16
Python Question

Sorting ordereddict not working

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?

Answer

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])
Comments