I have a dictionary that I am sending to an API, and unfortunately the API requires the dictionary to be in a very specific order. I am loading the dictionary from a file.
Right now json.load(fh, object_pairs_hook=OrderedDict)
does exactly what it's supposed to and orders the top level keys alphabetically, but I need the dictionary to be ordered differently.
Specific order:
{
"kind": "string",
"apiVersion": "string",
"metadata": {...},
"spec": {
"subKey": "string"
}
}
How do I specify the dictionary order of top and sub level keys with dictionaries that are loaded from a file?
In Python, the order of the items in OrderedDict
follow the same order that they were written into it.
So, if you want to control the order of the items when creating an OrderedDict
, you can write them in the order you want. For an existing OrderedDict
, you can read out, delete and write back each item in order.
In your example, if you need to adjust the orders of the items, you can do like:
orders = ("kind", "apiVersion", "metadata", "spec")
for key in orders:
v = object_pairs_hook[key]
del object_pairs_hook[key]
object_pairs_hook[key] = v
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