OrderedDict with a specific order in Python

I have a dictionary that I submit to the API, and unfortunately the API requires the dictionary to be in a very specific order. I am loading a dictionary from a file.

Right now, he json.load(fh, object_pairs_hook=OrderedDict)does exactly what he needs and orders the top-level keys in alphabetical order, but I need the dictionary to be ordered differently.

Specific order:

{
  "kind": "string",
  "apiVersion": "string",
  "metadata": {...},
  "spec": {
    "subKey": "string"
  }
}

How to specify the dictionary order of the upper and lower level keys with dictionaries loaded from a file?

+4
source share
2 answers

In Python, the order of elements in OrderedDictis executed in the same order in which they were written.

, OrderedDict, , . OrderedDict , .

, , :

orders = ("kind", "apiVersion", "metadata", "spec")
for key in orders:
    v = object_pairs_hook[key]
    del object_pairs_hook[key]
    object_pairs_hook[key] = v
+3

objects_pairs_hook, json OrderedDict :

SORT_ORDER = {
    "kind": 0,
    "apiVersion": 1,
    "metadata": 2,
    "spec": 3
}

d = json.load(fh)
d = OrderedDict(sorted(d.items(), key=lambda x: SORT_ORDER.get(x[0])))
+2

Source: https://habr.com/ru/post/1613541/


All Articles