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

>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!

Leave a Reply