0
d = {'A': ['A11117',
 '33465'
 '17160144',
 'A11-33465',
 '3040',
 'A11-33465 W1',
 'nor'], 'B': ['maD', 'vern', 'first', 'A2lRights']}

I have a dictionary d and I would like to sort the values based on length of characters. For instance, for key A the value A11-33465 W1 would be first because it contains 12 characters followed by 'A11-33465' because it contains 9 characters etc. I would like this output:

d = {'A': ['A11-33465 W1', 
' A11-33465',
 '17160144',
 'A11117',
 '33465',
 '3040',
 'nor'], 
'B': ['A2lRights',
'first',
'vern',
'maD']}

(I understand that dictionaries are not able to be sorted but I have examples below that didn't work for me but the answer contains a dictionary that was sorted)

I have tried the following

python sorting dictionary by length of values

print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))

Sort a dictionary by length of the value

sorted_items = sorted(d.items(), key = lambda item : len(item[1]))
newd = dict(sorted_items[-2:])

How do I sort a dictionary by value?

import operator
sorted_x = sorted(d.items(), key=operator.itemgetter(1))

But they both do not give me what I am looking for.

How do I get my desired output?

ChiBay
  • 189
  • 1
  • 6

1 Answers1

3

You are not sorting the dict, you are sorting the lists inside it. The simplest will be a loop that sorts the lists in-place:

for k, lst in d.items():
    lst.sort(key=len, reverse=True)

This will turn d into:

{'A': ['3346517160144', 'A11-33465 W1', 'A11-33465', 'A11117', '3040', 'nor'], 
 'B': ['A2lRights', 'first', 'vern', 'maD']}

If you want to keep the original data intact, use a comprehension like:

sorted_d = {k: sorted(lst, key=len, reverse=True) for k, lst in d.items()}
user2390182
  • 72,016
  • 6
  • 67
  • 89