0

I use Python 3.7 to build a dictionary, and want to sort the dictionary by the value of keys.

For example, I have dictionary like this:

example

Dict = ["r_1":...; "r_10":...; "r_11":...;....; "r_2":...]

But I want it to be

Dict = ["r_1":...; "r_2":...; ....; "r_10":...]

I only find ways to sort keys or values, but no solution for sorting the value of keys.

** I found multiple question to sort keys only, but py3 will automatically sort them in the order of "r_1", "r_10", "r_11", ..., "r_2". Those questions are different from this one.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alice
  • 33
  • 5
  • it's not duplicated. I want to sort value of keys, not only the keys. Python 3 will automatically sort keys in the way that question asked. – Alice Jul 22 '19 at 16:06
  • Where is the `dict`? Dictionaries don't use `[ ]` notation. Also your picture is of a table. Please make sure you have a minimal, complete, and VERIFIABLE example. Its also confusing why you are using `;`. – Error - Syntactical Remorse Jul 22 '19 at 16:10
  • Also you shouldn't use `Dict` as a variable name since `dict` is a keyword (though they won't overwrite each other). – Error - Syntactical Remorse Jul 22 '19 at 16:11
  • As I understand you want to treat the part of the string of the keys after _ as a number and sort on that, so you need to extract that out and sort on that number with some lambda function ... – Bruno Vermeulen Jul 22 '19 at 16:27

3 Answers3

3

Use OrderedDict:

from collections import OrderedDict

d = {"r_1": 1, "r_10": 10, "r_2": 2}
sd = sorted(d.items(), key=lambda x: int(x[0].split("_")[-1]))
sorted_d = OrderedDict(sd)

for k, v in sorted_d.items():
    print("{}: {}".format(k, v))

r_1: 1
r_2: 2
r_10: 10
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10
  • 1
    Thanks! I'm almost angry that some people didn't read question carefully and pick up the minor error rather than truly answer my question, but your answer is really help me! – Alice Jul 22 '19 at 17:14
  • Hi @Alice. If you still believe that the question is not a duplicate, you can discuss that in the comments under the question. It looks like people responded to that and believe that it is still a duplicate. You could ping `Error - Syntactical Remorse` under the question, as he/she is a close voter. – halfer Jul 23 '19 at 22:06
1

ok. I figure out the way sort it but will change the dictionary to list. It's:

Dict = sorted(Dict.items(), key = lambda kv:int(''.join(filter(str.isdigit, kv[0].split("_")[-1]))))
halfer
  • 19,824
  • 17
  • 99
  • 186
Alice
  • 33
  • 5
-1
>>>x= sorted(Dict.items())
>>>x
halfer
  • 19,824
  • 17
  • 99
  • 186
Shivam Mehrotra
  • 393
  • 2
  • 6