0

In Python I have a dict and want it sorted depending on the order of values matching the keys in the dict that are stored in a list. Assume the following:

value_dict = {"Alpha": "The Alpha", "Beta": "The Beta", "Gamma": "The Gamma"}
key_order = ["Beta", "Gamma", "Alpha"]

So in this case I would like the dict to be sorted so the key "Beta" comes first followed by "Gamma" and then "Alpha".

Any good ideas how I would do that?

Joakim
  • 195
  • 1
  • 9
  • Can't see how an OrderedDict would solve this. Since 3.6 dicts are ordered so that is not the problem here. – Joakim Dec 02 '18 at 22:09
  • Sort a dictionary by value: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – Frank Dec 02 '18 at 22:16

2 Answers2

2

Use OrderedDict

value_dict = {"Alpha": "The Alpha", "Beta": "The Beta", "Gamma": "The Gamma"}
key_order = ["Beta", "Gamma", "Alpha"]

# OrderedDict will keep the sequence intact
from collections import OrderedDict
OrderedDict(zip(key_order, [value_dict[i] for i in key_order]))

# OrderedDict([('Beta', 'The Beta'),
#              ('Gamma', 'The Gamma'),
#              ('Alpha', 'The Alpha')])
meW
  • 3,832
  • 7
  • 27
1

Try this out (using sorted() with key function) : sorted(value_dict.items(), key=lambda pair: key_order.index(pair[0]))

Kobip
  • 114
  • 1
  • 8