0

I have a list of dictionaries

[{'abc':1},{'abcd':2},{'ab':1}]

Based on length of key list has to sorted

[{'abcd':2},{'abc':1},{'ab':1}]
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56

2 Answers2

1

If you want to sort by the longest key:

l = [{'abc':1},{'abcd':2},{'ab':1}]
l.sort(key=lambda x: len(next(iter(x))), reverse=True)
print(l)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

If u like to sort by 1st key it's gonna be this:

l.sort(lambda a, b: -cmp(len(a.keys()[0]), len(b.keys()[0])))

However if you want to sort by max key, here the answer:

def maxKeyLen(d): return max(len(k) for k in d.keys())
l.sort(lambda a, b: -cmp(maxKeyLen(a), maxKeyLen(b)))
Mux
  • 348
  • 1
  • 6
  • when we haev list of dictionaries inside dictionaries [{'abc':{'count':1}},{'abcd:{'count:2'}'}], sorting this list based on 'count' , is it possible – user3522967 Mar 05 '15 at 11:22