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,246
  • 3
  • 34
  • 50

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
  • 963,270
  • 265
  • 3,804
  • 3,187
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
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
  • 328
  • 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