-
Notifications
You must be signed in to change notification settings - Fork 18
/
print_dictionary.py
51 lines (37 loc) · 1.24 KB
/
print_dictionary.py
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
"""
Recursively print dictionary (e.g. use with collections.defaultdict(dict))
"""
def _quote_if_string(value):
if isinstance(value, str):
return "\"" + value + "\""
else:
return str(value)
def _prepend_if_multiline(s, prepend_spaces_count):
result = ""
prepend = " " * prepend_spaces_count
for c in s:
if c == "\n":
result += c + prepend
else:
result += c
return result
def _print_dictionary(d, name, prepend=""):
""" Recursively print dictionary """
print(prepend + _quote_if_string(name) + ": {")
for k in d.keys():
if isinstance(d[k], dict):
_print_dictionary(d[k], k, prepend=prepend+" ")
else:
beginning = prepend + " " + _quote_if_string(k) + ": "
print(beginning + _prepend_if_multiline(
_quote_if_string(d[k]), len(beginning)) + ",")
print(prepend + "},")
def print_dictionary(d, name):
""" Recursively print dictionary """
print(name, "= {")
for k in d.keys():
if isinstance(d[k], dict):
_print_dictionary(d[k], k, prepend=" ")
else:
print(" " + _quote_if_string(k) + ": " + _quote_if_string(d[k]) + ",")
print("}")