How to reorder the keys of a dictionary?
Question:
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
}
...
Answers:
You cannot sort a dictinary because dictionaries have no order.
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
}
]
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"
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
}
...
You cannot sort a dictinary because dictionaries have no order.
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 } ]
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"