1

I have a dictionary:

test_dict = {"1": "one", "3": "three", "2": "two"}

I'd like to create an array of values, but sorted by key, to get something like this:

test_array = ["one", "two", "three"]

Normally, I retrieve values by using test_dict.values(), but since dictionaries are unordered, it messes up my array.

lorgan
  • 13
  • 2
  • 1
    @accdias: `sorted()` returns a list, lists don't have a `.values()` method. – Martijn Pieters Dec 28 '19 at 14:11
  • Yeah... I know and that's why I deleted the comment. I meant to write this `dict(sorted(test_dict.items())).values()`. Kind of a hack though. – accdias Dec 28 '19 at 14:13
  • Someone posted this `[x[1] for x in sorted(test_dict.items(), key=lambda x: int(x[0]))]` which seems to do the trick. Thanks! – lorgan Dec 28 '19 at 14:22
  • If you want without using OrderedDict you can use something like this `values = [x[1] for x in sorted(data.items(), key = lambda x:x[0])]` – mohammed wazeem Dec 28 '19 at 14:48

1 Answers1

2

You can try this:

test_dict = {"1": "one", "3": "three", "2": "two"}

print([x[1] for x in sorted(test_dict.items(), key=lambda x: int(x[0]))])
# ['one', 'two', 'three']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75