0

I have a list containing dictionaries similar to the below example. I want to try and sort the list using tbl_nm and seq. Not sure how to make it happen. Example List with Dictionaries

[
    {"tbl_nm": "Table 1", "seq": 2, "data": "datapoint"},
    {"tbl_nm": "Table 1", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 1", "seq": 3, "data": "datapoint"},
    {"tbl_nm": "Table 2", "seq": 2, "data": "datapoint"},
    {"tbl_nm": "Table 2", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 3", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 4", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 4", "seq": 2, "data": "datapoint"}
]

Expected Output:-

[
    {"tbl_nm": "Table 1", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 1", "seq": 2, "data": "datapoint"},
    {"tbl_nm": "Table 1", "seq": 3, "data": "datapoint"},
    {"tbl_nm": "Table 2", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 2", "seq": 2, "data": "datapoint"},
    {"tbl_nm": "Table 3", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 4", "seq": 1, "data": "datapoint"},
    {"tbl_nm": "Table 4", "seq": 2, "data": "datapoint"}
]
martineau
  • 119,623
  • 25
  • 170
  • 301
Eunice Dhivya
  • 309
  • 4
  • 13
  • @Itworksonmypc Perhaps because "there is no effort shown by the OP" thing, although I don't get the point to be honest, except when the question is obviously a homework assignment. – j1-lee Jan 22 '22 at 18:56
  • This is true. There is both Python and pythkn 3 tagged in the question, yet there is no Python code to speak of, which is troubling to say the least. I agree question might be legit though, however lack of effort sways me from upvoting this post. – rv.kvetch Jan 22 '22 at 18:57

1 Answers1

4

You can use .sort(), passing in a lambda function as the key parameter. The key is a tuple with tbl_nm as the first element, and seq as the second element. This means we sort on tbl_nm first, then use seq if two dictionaries have the same tbl_nm value.

data.sort(key=lambda x: (x["tbl_nm"], x["seq"]))
print(data)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33