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 second dictionary based on value sequence of first

I am trying to sort the dictionary based on the value of the first dictionary sequence
Example:
s = {"J":1, "R":2, "E":3, "L":4]
o = {"J":"V140", "E":"21:45", "R":"SUN MON TUE WED THU", "L":"V2730"]

expecting the o dictionary in the key order of s
o = {"J":"V140","R":"SUN MON TUE WED THU", "E":"21:45", "L":"V2730"}

I looked at the example and solution given Sort list of dictionaries by another list and tried different ways to modify it as I need something similar to it, but nothing worked

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

>Solution :

You can sort the keys of the first dict by their values, and then build a new dict from the second dict with the sorted key order:

{k: o[k] for k in sorted(s, key=s.get)}

Demo: Try it online!

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