Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a complex nested dictionary to a nested list

Tags:

python

What is the best way to sort a nested dictionary in Python 2.6 by value? I would like to sort by the length of the inner dictionary followed by the inner dictionary with the largest value. For example:

d = {1: {'AA': {'a': 100, 'b': 1, 'c': 45}},
     2: {'AA': {'c': 2}},
     3: {'BB': {'d': 122, 'a': 4, 't': 22, 'r': 23, 'w': 12}},
     4: {'CC': {'y': 12, 'g': 15, 'b': 500}}}

The desired solution is a nested list:

lst = [[3, 'BB', {'d': 122, 'a': 4, 't': 22, 'r': 23, 'w': 12}],
       [4, 'CC', {'y': 12, 'g': 15, 'b': 500}],
       [1, 'AA', {'a': 100, 'b': 1, 'c': 45}],
       [2, 'AA', {'c': 2}]]
like image 614
user1728853 Avatar asked Feb 27 '26 14:02

user1728853


1 Answers

With your corrected data-structure:

d = {1: {'AA': {'a': 100, 'b': 1, 'c': 45}},
     2: {'AA': {'c': 2}},
     3: {'BB': {'d': 122, 'a': 4, 't': 22, 'r': 23, 'w': 12}},
     4: {'CC': {'y': 12, 'g': 15, 'b': 500}}}

def sortkey(x):
   num,d1 = x
   key,d2 = d1.items()[0] #Some may prefer `next(d.iteritems())`
   return len(d2),max(d2.values())

exactly_how_you_want_it = [([k] + v.keys() + v.values()) for k,v in 
                           sorted(d.items(),reverse=True,key=sortkey)]

for item in exactly_how_you_want_it:
   print item

results:

[3, 'BB', {'a': 4, 'r': 23, 'd': 122, 'w': 12, 't': 22}]
[4, 'CC', {'y': 12, 'b': 500, 'g': 15}]
[1, 'AA', {'a': 100, 'c': 45, 'b': 1}]
[2, 'AA', {'c': 2}]
like image 107
mgilson Avatar answered Mar 02 '26 05:03

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!