7

I have multiple dictionaries inside the list. I want to sort the dictionary with the custom key. In my case, I want to sort it using Date key. By that, I mean to move the Date key to the first position. What is the efficient way to sort the dictionary using Date key?

PS: I don't want to sort by the value of the Date.

[
   {
      
      "AmazonS3":6.54,
      "AmazonEC2":27.55,
      "AmazonCloudWatch":0.51,
      "Date":"2020-07-01"
   },
   {
      "AmazonEC2":27.8,
      "Date":"2020-07-02"
   },
   {
      "AmazonElastiCache":0.01,
      "AmazonEC2":35.34,
      "Date":"2020-07-03"
   }
]

Expected output:

...
   {
      "Date":"2020-07-03",
      "AmazonElastiCache":0.01,
      "AmazonEC2":35.34
   }
...
Asocia
  • 5,935
  • 2
  • 21
  • 46
Muhaddis
  • 530
  • 7
  • 18
  • 1
    Why do you want to do this? You can't index a dict with 0, 1, 2... so why do you want to rely on positioning of the keys? – Asocia Jul 28 '20 at 13:50
  • 1
    Does this answer your question? [sorting dictionary python 3](https://stackoverflow.com/questions/11089655/sorting-dictionary-python-3) – Bram Vanroy Jul 28 '20 at 13:50
  • @Asocia This sounds vague, but I am using `json2html` module to convert this data to HTML and email the user. I want to display the date on top of the table. This is a complex list with 30+ dictionaries. – Muhaddis Jul 28 '20 at 13:54
  • Are you creating the json that you are converting? If so then simply add the items to the dict in the order you want. Or follow the second answer to the post linked by @BramVanroy – plum 0 Jul 28 '20 at 13:59
  • I am using `json.dumps(my_data)` – Muhaddis Jul 28 '20 at 14:02
  • You are not sorting dictionies, you're sorting a list of them. There are standard ways to sort lists that would allow you to do exactly what's needed (hint: it''s often called a "key" function). – martineau Jul 28 '20 at 14:05

3 Answers3

9

If you are using a Python version that preserves key insertion order (i.e. 3.7 or newer) you can do this:

print([{"Date": di["Date"], **di} for di in my_list])
[
  {
     'Date': '2020-07-01', 
     'AmazonS3': 6.54, 
     'AmazonEC2': 27.55, 
     'AmazonCloudWatch': 0.51
  }, 
  {
     'Date': '2020-07-02', 
     'AmazonEC2': 27.8
  }, 
  {
     'Date': '2020-07-03', 
     'AmazonElastiCache': 0.01,  
     'AmazonEC2': 35.34
  }
]
Asocia
  • 5,935
  • 2
  • 21
  • 46
3

I believe you can use OrderedDict's move_to_end to do this.

dict = OrderedDict.fromkeys("qwerty")
dict.move_to_end("t", last=False)
"".join(dict.keys())
"tqwery"
Spaceglider
  • 97
  • 11
-4

You cannot sort a dictinary because dictionaries have no order.

One Nose
  • 52
  • 1
  • 7
  • 10
    Dictionaries do have order since Python3.7. And there is a data type called `OrderedDict` in `collections`. – Asocia Jul 28 '20 at 13:53