0

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 ?

  • 7
    Dicts are unordered and cannot be sorted. Use OrderedDict instead – Bhargav Rao Oct 29 '15 at 20:00
  • You only see that ordering when you print the dictionary. It's stored in memory unordered, because it's a hash table. Look up "printing dict in sorted order" if you want to see it displayed differently. – skrrgwasme Oct 29 '15 at 20:02
  • 1
    Possible duplicate of [How can I sort a dictionary by key?](http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – skrrgwasme Oct 29 '15 at 20:11
  • You only want the inner dict sorted "in the case of conflicting values?" This suggests you are collecting votes. Is the decending order given in your example desired output a case of VB > NN > PP or is that the value 3 has more keys than the value 2? – Bennett Brown Oct 29 '15 at 20:19

2 Answers2

2

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))
Bennett Brown
  • 5,234
  • 1
  • 27
  • 35
  • This solution given, I think it is more likely you want to be using some other data structure. What is your intended use? – Bennett Brown Oct 29 '15 at 20:17
0

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)])}
martineau
  • 119,623
  • 25
  • 170
  • 301