A
A
agent_22032021-07-21 19:19:34
Python
agent_2203, 2021-07-21 19:19:34

How to sort dict by list's sizes in their values?

There is the following dict:

dct = {1: [1, 2, 3, 4, 5], 2:[1, 2, 3], 3:[1, 2, 3, 4, 5, 6, 7, 8, 9], 4:[1, 2, 3, 4, 5, 6, 7, 8], 5:[1, 2, 3, 4, 5, 6, 7, 8, 9]}


How can I sort a dict so that all keys with values ​​go in ascending order of the size of list in values? Accordingly, the output should have the following format

{2:[1, 2, 3], 1: [1, 2, 3, 4, 5] , 4:[1, 2, 3, 4, 5, 6, 7, 8], 3:[1, 2, 3, 4, 5, 6, 7, 8, 9], 5:[1, 2, 3, 4, 5, 6, 7, 8, 9]}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wispik, 2021-07-21
@agent_2203

res = dict(sorted(dct.items(), key=lambda item: len(item[1])))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question