Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderedDict with specific order in Python

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?

like image 398
SiennaD. Avatar asked Oct 28 '15 18:10

SiennaD.


1 Answers

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
like image 101
stanleyli Avatar answered Sep 23 '22 18:09

stanleyli