Sorting a dictionary of dictionaries

Question:

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.

Asked By: Bramat

||

Answers:

A dictionary is not like a list – it has no particular ‘order’. It is simply a collection of keys and their respective values, so dictionaries cannot be sorted.

If you wish to read more about it, the docs give a good overview of the datatype.

Answered By: Cole

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})])
Answered By: SparkAndShine

Not sure what exactly it is you are trying to accomplish. If you want to do something along the following lines, then without using OrderedDict:

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

for k, v in sorted(dct_of_dcts.items(), key=lambda e: e[1]["order"]):
    print(k, v)

Will print either:

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

Or:

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

In case you just want to output/print the dictionary of dictionaries in the exact order you specified, this would work:

for k, v in sorted(dct_of_dcts.items(), key=lambda e: e[1]["order"]):
    print(k, sorted(v.items()))

Output:

ghi [('name', 'Tim'), ('order', 1)]
def [('name', 'Allen'), ('order', 2)]
abc [('name', 'Joey'), ('order', 3)]
Answered By: Spherical Cowboy
from _collections import OrderedDict
d = {"abc":{"name":"Joey","order":3},
     "def":{"name":"Allen","order":2},
     "ghi":{"name":"Tim","order":1}}
_sorted = OrderedDict(sorted(d.items(), key=lambda x: x[1]["order"]))

Then:

print(_sorted)
OrderedDict([('ghi', {'order': 1, 'name': 'Tim'}), ('def', {'order': 2, 'name': 'Allen'}), ('abc', {'order': 3, 'name': 'Joey'})])

And:

print(_sorted["ghi"])
{'order': 1, 'name': 'Tim'}

dictionaries are unordered, if you want one that is ordered you have to use OrderedDict.

Answered By: Lomtrur

You can use OrderedDict

from collections import OrderedDict

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

order_dic = OrderedDict(sorted(dic.items(), key=lambda x: x[1]['order'], reverse=False))
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.