Coverage for jutil/dict.py : 79%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import re
2from collections import OrderedDict
3from typing import List, Sequence, Tuple, Any, Dict, TypeVar
4from django.utils.text import capfirst
7R = TypeVar('R')
8S = TypeVar('S')
11def sorted_dict(d: Dict[Any, R]) -> Dict[Any, R]:
12 """
13 Returns OrderedDict sorted by ascending key
14 :param d: dict
15 :return: OrderedDict
16 """
17 return OrderedDict(sorted(d.items()))
20def choices_label(choices: Sequence[Tuple[S, str]], value: S) -> str:
21 """
22 Iterates (value,label) list and returns label matching the choice
23 :param choices: [(choice1, label1), (choice2, label2), ...]
24 :param value: Value to find
25 :return: label or None
26 """
27 for key, label in choices: 27 ↛ 30line 27 didn't jump to line 30, because the loop on line 27 didn't complete
28 if key == value: 28 ↛ 27line 28 didn't jump to line 27, because the condition on line 28 was never false
29 return label
30 return ''
33def _dict_to_html_format_key(k: str) -> str:
34 if k.startswith('@'):
35 k = k[1:]
36 k = k.replace('_', ' ')
37 k = re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', k)
38 parts = k.split(' ')
39 out: List[str] = [str(capfirst(parts[0].strip()))]
40 for p in parts[1:]:
41 p2 = p.strip().lower()
42 if p2: 42 ↛ 40line 42 didn't jump to line 40, because the condition on line 42 was never false
43 out.append(p2)
44 return ' '.join(out)
47def _dict_to_html_r(data: Dict[str, Any], margin: str = '', format_keys: bool = True) -> str:
48 if not isinstance(data, dict): 48 ↛ 49line 48 didn't jump to line 49, because the condition on line 48 was never true
49 return '{}{}\n'.format(margin, data)
50 out = ''
51 for k, v in sorted_dict(data).items():
52 if isinstance(v, dict):
53 out += '{}{}:\n'.format(margin, _dict_to_html_format_key(k) if format_keys else k)
54 out += _dict_to_html_r(v, margin + ' ', format_keys=format_keys)
55 out += '\n'
56 elif isinstance(v, list): 56 ↛ 57line 56 didn't jump to line 57, because the condition on line 56 was never true
57 for v2 in v:
58 out += '{}{}:\n'.format(margin, _dict_to_html_format_key(k) if format_keys else k)
59 out += _dict_to_html_r(v2, margin + ' ', format_keys=format_keys)
60 out += '\n'
61 else:
62 out += '{}{}: {}\n'.format(margin, _dict_to_html_format_key(k) if format_keys else k, v)
63 return out
66def dict_to_html(data: Dict[str, Any], format_keys: bool = True) -> str:
67 """
68 Formats dict to simple pre-formatted html (<pre> tag).
69 :param data: dict
70 :param format_keys: Re-format 'additionalInfo' and 'additional_info' type of keys as 'Additional info'
71 :return: str (html)
72 """
73 return '<pre>' + _dict_to_html_r(data, format_keys=format_keys) + '</pre>'