Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading