-1

I have a dict which I want to sort by their values. After that I want the order of the keys to be put in an array. I tried some code, but all just output the values if It was sorted by the values or the keys if it was sorted by the keys. This is my dict:

{0: 1.0, 1: 22.0, 2: 30.0, 3: 8.0, 4: 17.0, 5: 9.0, 6: 13.0, 7: 21.0, 8: 
24.0, 9: 18.0, 10: 14.0, 11: 2.0, 12: 20.0, 13: 23.0, 14: 19.0, 15: 15.0, 16: 
6.0, 17: 26.0, 18: 11.0, 19: 5.0, 20: 29.0, 21: 7.0, 22: 12.0, 23: 27.0, 24: 
25.0, 25: 16.0, 26: 3.0, 27: 4.0, 28: 28.0, 29: 10.0}

It should return something like this:

[0,11,26,27,19,16, etc]
T.v.L.
  • 43
  • 8
  • 1
    `sorted(dictionary, key=dictionary.get)` is all you need; it return `[0, 11, 26, 27, 19, 16, 21, 3, 5, 29, 18, 22, 6, 10, 15, 25, 4, 9, 14, 12, 7, 1, 13, 8, 24, 17, 23, 28, 20, 2]` for your sample input. – Martijn Pieters Jun 14 '18 at 19:05

2 Answers2

1

Given your dictionary d:

result = sorted(d, key=d.get)

sorted(d) without a key argument would iterate over the keys in d create a list from it and give it back with the natural sort order. (It iterates over keys because that is the normal iteration for a dictionary.) The key argument allows you to pass in a function that returns a proxy value to sort by for each item. After sorting the proxy values are discarded and you just get the items you wanted sorted. key=d.get uses the original dictionary to lookup the value associated with each item.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • Thank you. this works. For my understanding, the d.get refers to the values of the dictionary? – T.v.L. Jun 14 '18 at 19:14
-1

This might help:

def get_keys_ordered_using_values(data):
    return list(map(lambda y: y[0], sorted(data.items(), key=lambda x: x[1])))

my_data = {0: 1.0, 1: 22.0, 2: 30.0, 3: 8.0, 4: 17.0, 5: 9.0, 6: 13.0, 7: 21.0, 
           8: 24.0, 9: 18.0, 10: 14.0, 11: 2.0, 12: 20.0, 13: 23.0, 14: 19.0, 15: 15.0, 
        16: 6.0, 17: 26.0, 18: 11.0, 19: 5.0, 20: 29.0, 21: 7.0, 22: 12.0, 23: 27.0, 
        24: 25.0, 25: 16.0, 26: 3.0, 27: 4.0, 28: 28.0, 29: 10.0}

print(get_keys_ordered_using_values(my_data))
tkhurana96
  • 919
  • 7
  • 25