Anupam Alur
Anupam Alur

Reputation: 13

Sorting a dict of dict in python

I am pretty new to python and I have a doubt

I have a dict of dict which looks like

{"boy" : { "NN" : 3 ,"VB" : 3, "PP" : 2 } }

In case of a conflict of values as shown in the example above , I want to sort the internal dict based on their keys in descending order. The answer should look like :

{"boy" : {"VB" : 3, "NN" : 3, "PP":2} }

How can I do that ?

Upvotes: 0

Views: 123

Answers (2)

martineau
martineau

Reputation: 123463

You could sort the inner dictionaries like this:

from collections import OrderedDict

dict_of_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }

# sort inner dictionaries by descending key values
dict_of_dict = {key: OrderedDict(sorted(inner_dict.items(), reverse=True))
                    for key, inner_dict in dict_of_dict.items()}

print(dict_of_dict) # -> {'boy': OrderedDict([('VB', 3), ('NN', 3), ('AA', 2)])}

Upvotes: 0

Bennett Brown
Bennett Brown

Reputation: 5373

Use an OrderedDict.

from collections import OrderedDict
outer_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }
for key in outer_dict:
    inner_dict = outer_dict[key]
    outer_dict[key] = OrderedDict(sorted(inner_dict.items(), reverse=True))

Upvotes: 2

Related Questions