I have dictionary which has {key : []}
format. I need to prepare a list sorted based on the length of the value (length of the list). What's the best way to accomplish this?
Asked
Active
Viewed 2,560 times
0

sarat
- 10,512
- 7
- 43
- 74
-
A list of what? The values sorted by length? – Yuval Adam Oct 27 '12 at 17:42
-
Duplicate [sorting a list of dictionary values by date in python][1]? [1]: http://stackoverflow.com/questions/652291/sorting-a-list-of-dictionary-values-by-date-in-python?rq=1 – Anton Bessonov Oct 27 '12 at 17:44
1 Answers
4
If you're looking for the values sorted by length, and assuming dict d
:
lists_by_length = sorted(d.values(), key=len)
Also see Sort a Python dictionary by value

Community
- 1
- 1

Yuval Adam
- 161,610
- 92
- 305
- 395
-
the list consists of objects from `Vertex` class and the following errors are occured `AttributeError: Vertex instance has no attribute '__len__'` – sarat Oct 27 '12 at 18:06
-
The the values aren't naive python `list`s, or objects that implement `__len__`. How do you extract the `Vertex` object's length? – Yuval Adam Oct 27 '12 at 18:23
-
Thanks for the answer, I added a global function to process the vertex class. – sarat Oct 27 '12 at 19:27