I have a list of dictionaries where each dictionary can have a different length (different number of keys). How can I sort my list so that the longest dictionary is at list[0]
?
Asked
Active
Viewed 2,178 times
1
-
All the answers have worked correctly. I chose the one proposed by Dima Kudosh as it does not require a new list to be created to store the sorted list. – KOB Jan 10 '16 at 18:19
4 Answers
5
Sort the list with key=len
>>> d0
{'a': 100, 'c': 150, 'b': 5, 'd': 60}
>>> d1
{1: 'ONE', 2: 'TWO'}
>>> d2
{3: 'THREE', 4: 'FOUR'}
>>> d3
{1:'ONE',2:'TWO',3:'THREE'}
l = [d0,d1,d2,d3]
>>> sorted(l, key=len, reverse=True)
[{'a': 100, 'c': 150, 'b': 5, 'd': 60}, {1: 'ONE', 2: 'TWO', 3: 'THREE'}, {1: 'ONE', 2: 'TWO'}, {3: 'THREE', 4: 'FOUR'}]
>>>
>>> l.sort(key=len, reverse=True) #in list sorting

Iron Fist
- 10,739
- 2
- 18
- 34
2
You can use sort method in your list:
list_with_dicts.sort(key=lambda x: -len(x))

Dima Kudosh
- 7,126
- 4
- 36
- 46
1
You could pass to sorted
key
parameter with length of your dicts:
sorted_list = sorted(l, key = lambda x: len(x.keys())
Or just
sorted_list = sorted(l, key = len)
Where l
is a list with your dicts

Anton Protopopov
- 30,354
- 12
- 88
- 93
1
You can use sorted
method:
newList = sorted(list, key=lambda k:len(k), reverse = True)
or without create a new list:
list = sort(key=lambda k:len(k), reverse = True)

ᴀʀᴍᴀɴ
- 4,443
- 8
- 37
- 57