Home > Software engineering >  Sort a dict by values, given that a key contains many values
Sort a dict by values, given that a key contains many values

Time:09-29

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' ] 
 }
 

CodePudding user response:

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()

CodePudding user response:

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])
  • Related