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}]
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}]
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)
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)))