1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
# -*- coding: utf-8 -*-
"""Temporary helper functions to ease OrderedDict removal."""
def dict_slice(obj, start=None, stop=None, step=None):
"""Slice the given dict.
Args:
obj (dict): The dictionary to work on.
start (int, None): The start index.
stop (int, None): The stop index.
step (int, None): The step (currently not used).
Returns:
dict: The sliced dictionary.
"""
all_keys = list(obj.keys())
if start:
if stop:
return dict(
zip(
all_keys[start:stop],
list(map(lambda key: obj[key], all_keys[start:stop])),
)
)
else:
return dict(
zip(all_keys[start:], list(map(lambda key: obj[key], all_keys[start:])))
)
else:
if stop:
return dict(
zip(all_keys[:stop], list(map(lambda key: obj[key], all_keys[:stop])))
)
else:
start = 0
stop = len(all_keys)
return dict(
zip(
all_keys[start:stop],
list(map(lambda key: obj[key], all_keys[start:stop])),
)
)
def dict_sort(obj, key=None):
"""Return a sorted dict.
Args:
obj (dict): The dictionary to work on.
key (callable): A callable to generate the key.
Returns:
dict: The sorted dictionary.
"""
new_dict = {}
for k in sorted(obj, key=key):
new_dict[k] = obj[k]
return new_dict
|