Nemo Nemo - 2 months ago 5x
JSON Question

How to process python dictionary items in the order of value item?

I get the following JSON from a web service. How to get an ordered collection from the following JSON in Python. I want to process key value pairs in the ascending order of "order" number.

"key1": {
"order": 10,
"name": "somenameZ"
"key2": {
"order": 3,
"name": "somenameY"
"key3": {
"order": 8,
"name": "somenameX"


Sort the dict.items() result with a custom key:

ordered = sorted(outerdict.items(), key=lambda kv: kv[1]['order'])
for key, item in ordered:
    # ...

If you only need the nested dictionaries, and not the outer keys, you could do the same for dict.values():

ordered = sorted(outerdict.values(), key=lambda v: v['order'])
for item in ordered:
    # ...