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
}
...
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.
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.
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.
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 } ]
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With