| 1 |
"""Temporary helper functions to ease OrderedDict removal.""" |
| 2 |
|
| 3 |
# Standard Library Imports |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from typing import Callable |
| 7 |
|
| 8 |
|
| 9 |
def dict_slice( |
| 10 |
obj: dict, |
| 11 |
start: None | int = None, |
| 12 |
stop: None | int = None, |
| 13 |
step: None | int = None, |
| 14 |
) -> dict: |
| 15 |
"""Slice the given dict. |
| 16 |
|
| 17 |
Args: |
| 18 |
obj (dict): The dictionary to work on. |
| 19 |
start (None | int): The start index. |
| 20 |
stop (None | int): The stop index. |
| 21 |
step (None | int): The step (currently not used). |
| 22 |
|
| 23 |
Returns: |
| 24 |
dict: The sliced dictionary. |
| 25 |
""" |
| 26 |
all_keys = list(obj.keys()) |
| 27 |
if start: |
| 28 |
if stop: |
| 29 |
return dict( |
| 30 |
zip(all_keys[start:stop], [obj[key] for key in all_keys[start:stop]]) |
| 31 |
) |
| 32 |
return dict(zip(all_keys[start:], [obj[key] for key in all_keys[start:]])) |
| 33 |
if stop: |
| 34 |
return dict(zip(all_keys[:stop], [obj[key] for key in all_keys[:stop]])) |
| 35 |
start = 0 |
| 36 |
stop = len(all_keys) |
| 37 |
return dict(zip(all_keys[start:stop], [obj[key] for key in all_keys[start:stop]])) |
| 38 |
|
| 39 |
|
| 40 |
def dict_sort(obj: dict, key: None | Callable = None) -> dict: |
| 41 |
"""Return a sorted dict. |
| 42 |
|
| 43 |
Args: |
| 44 |
obj (dict): The dictionary to work on. |
| 45 |
key (None | Callable): A callable to generate the key. |
| 46 |
|
| 47 |
Returns: |
| 48 |
dict: The sorted dictionary. |
| 49 |
""" |
| 50 |
new_dict = {} |
| 51 |
for k in sorted(obj, key=key): |
| 52 |
new_dict[k] = obj[k] |
| 53 |
return new_dict |
| 54 |
|
| 55 |
|
| 56 |
def swap_dict_keys_values(dict_in: dict) -> dict: |
| 57 |
"""Swap dictionary keys and values. |
| 58 |
|
| 59 |
Args: |
| 60 |
dict_in (dict): The dictionary to swap. |
| 61 |
|
| 62 |
Returns: |
| 63 |
dict: The swapped dictionary. |
| 64 |
""" |
| 65 |
return {v: k for k, v in dict_in.items()} |