Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary of Dictionaries - Python

I have a dictionary of dictionaries, that looks something like this:

"abc": {
    "name": "Joey",
    "order": 3
    },
"def": {
    "name": "Allen",
    "order": 2
    },
"ghi": {
    "name": "Tim",
    "order": 1
    }

Now, I would like to sort this dictionary according to the "order" value.

Meaning, the sorted dictionary will look like:

"ghi": {
    "name": "Tim",
    "order": 1
    }
"def": {
    "name": "Allen",
    "order": 2
    },
"abc": {
    "name": "Joey",
    "order": 3
    }

How can I do this? I found ways to sort a list of dictionaries, but not a dictionary of dictionaries.

like image 305
Bramat Avatar asked Jan 05 '23 11:01

Bramat


1 Answers

Use sorted to sort by "order" and collections.OrderedDict to store the result,

import collections

d = {
    "abc": {
        "name": "Joey",
        "order": 3
        },
    "def": {
        "name": "Allen",
        "order": 2
        },
    "ghi": {
        "name": "Tim",
        "order": 1
        }
    }

result = collections.OrderedDict(sorted(d.items(), key=lambda t:t[1]["order"]))

# Output
print(result)
OrderedDict([('ghi', {'name': 'Tim', 'order': 1}), 
            ('def', {'name': 'Allen', 'order': 2}), 
            ('abc', {'name': 'Joey', 'order': 3})])
like image 99
SparkAndShine Avatar answered Jan 14 '23 08:01

SparkAndShine