Sort a dict by values, given that a key contains many values

Question:

I am trying to sort a dict by values, where each of my keys have many values.
I know It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless.

I tried this solutions, from another post but it doesn’t seem to work for my case :

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

or

dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

from this post
How do I sort a dictionary by value?

Also, I tried :

sorted(x, key=lambda x: x['key'])

But, there my dict is a string and it doesn’t work and It would not be the best option if I want to apply it in every keys, i would have to repeat the process for each of them.

Here is a sample of my dict :

{
'/Users/01': 
 ['V01File12.txt',
  'V01File01.txt',
  'V01File18.txt',
  'V01File15.txt',
  'V01File02.txt',
  'V01File11.txt' ] ,
 '/Users/02':
 ['V02File12.txt',
  'V02File01.txt',
  'V02File18.txt',
  'V02File15.txt',
  'V02File02.txt',
  'V02File11.txt' ]
}

and so on …

the expected output would be :

{'/Users/01': 
 ['V01File01.txt',
  'V01File02.txt',
  'V01File11.txt',
  'V01File12.txt',
  'V01File15.txt',
  'V01File18.txt' ] ,
 '/Users/02': 
 ['V02File01.txt',
  'V02File02.txt',
  'V02File11.txt',
  'V02File12.txt',
  'V02File15.txt',
  'V02File18.txt' ] 
 }
 
Asked By: Art

||

Answers:

If you want to sort the list inside each dictionary:

a ={
'/Users/01': 
 ['V01File12.txt',
  'V01File01.txt',
  'V01File18.txt',
  'V01File15.txt',
  'V01File02.txt',
  'V01File11.txt' ] ,
 '/Users/02':
 ['V02File12.txt',
  'V02File01.txt',
  'V02File18.txt',
  'V02File15.txt',
  'V02File02.txt',
  'V02File11.txt' ]  


for i in a:
        a[i] = sorted(a[i])
Answered By: Aric a.

So you’re not trying to sort the dict, you’re trying to sort the lists in it. I would just use a comprehension:

data = {k, sorted(v) for k, v in data.items()}

Or just alter the dict in place:

for v in data.values():
    v.sort()
Answered By: Jab

The best solution is the solution of @StevenRumblaski:

for b in a.values(): b.sort()
Answered By: Elicon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.