Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder the keys of a dictionary?

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
   }
...
like image 811
Muhaddis Avatar asked Jul 28 '20 13:07

Muhaddis


People also ask

Can I change order of keys in dictionary Python?

To sort a dictionary by key in Python, use a combination of the sort() and OrderedDict() methods. The OrderedDict() is a method of the Collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order.

Do dictionary keys have an order?

Answer. No, there is no guaranteed order for the list of keys returned by the keys() function. In most cases, the key list is returned in the same order as the insertion, however, that behavior is NOT guaranteed and should not be depended on by your program.

How do you change the order of a dictionary?

Yes, just go to the Preferences for the Dictionary app. There's a list there of all the possible dictionaries, which you can then drag to be in any order you like.


2 Answers

If you are using Python3.7 or greater 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
  }
]
like image 171
Asocia Avatar answered Oct 16 '22 04:10

Asocia


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"
like image 24
Spaceglider Avatar answered Oct 16 '22 04:10

Spaceglider