pyyeti.ytools.reorder_dict

pyyeti.ytools.reorder_dict(ordered_dict, keys, where)[source]

Copy and reorder an ordered dictionary

Note

This will also work for regular Python dict (dict) objects for Python 3.7+ where insertion order is guaranteed. See also collections.OrderedDict.

Parameters:
  • ordered_dict (instance of OrderedDict or other ordered mapping) – The ordered dictionary to copy and put in a new order. Must accept tuple of 2-tuples, eg, ((key1, value1), (key2, value2), ...) in its __init__ function.

  • keys (iterable) – Iterable of keys in the order desired. Note that all keys do not need to be included, just those where a new order is desired. For example, if you just want to ensure that ‘scltm’ is first:

    new_dict = reorder_dict(ordered_dict, ['scltm'], 'first')
    
  • where (string) – Either ‘first’ or ‘last’. Specifies where to put the reordered items in the final order.

Returns:

ordered dictionary object (same type as ordered_dict) – A new ordered dictionary, reordered as specified

Raises:

Examples

>>> from collections import OrderedDict
>>> from pyyeti.ytools import reorder_dict
>>> dct = OrderedDict((('one', 1),
...                    ('two', 2),
...                    ('three', 3)))
>>> dct
OrderedDict({'one': 1, 'two': 2, 'three': 3})
>>> reorder_dict(dct, ['three', 'two'], 'first')
OrderedDict({'three': 3, 'two': 2, 'one': 1})