File: util_dict.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (59 lines) | stat: -rw-r--r-- 1,585 bytes parent folder | download | duplicates (2)
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