Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reorder OrderedDict
def reorder_ordereddict(ordered_dict, key_order):
"""
Return a new OrderedDict using a source ordered_dict and key_order iterable.
Any keys in ordered_dict that are not in key_order will be added
in their original order to the end of the returned OrderedDict.
KeyError will be raised for keys in key_order that are not in ordered_dict.
Intended for specifiying the order of Form.fields without having to create
them in the required order.
"""
return OrderedDict(
[(k, ordered_dict[k]) for k in key_order]
+ [(k, ordered_dict[k]) for k in ordered_dict.keys() if k not in key_order]
)
# ordered_dict = OrderedDict([('a','A'),('b','B'),('c','C'),('d','D')])
# key_order = ('d','b')
# reorder_ordereddict(ordered_dict, key_order)
# >>> OrderedDict([('d', 'D'), ('b', 'B'), ('a', 'A'), ('c', 'C')])
#
# In a Form:
# key_order = ['fieldC', 'fieldB']
# self.fields = reorder_ordereddict(self.fields, key_order)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.