您可以像这样创建一个类,其__str__ 方法将格式化字典的输出:
class DictionaryFormatter():
def __init__(self, dictionary):
self.obj1 = dictionary
def __str__(self):
obj1_str = str(self.obj1)
obj1_str = obj1_str.replace("'", "")
obj1_str = obj1_str.replace(":", " =")
return f"obj1 = {obj1_str}"
d = {
"a": {"aa": 1, "ab": 2},
"b": {"ba": 3, "bb": 5},
"c": [1, 2, 4]
}
print(DictionaryFormatter(d))
print("obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1 2 4]}")
输出:
obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1, 2, 4]}
obj1 = {a = {aa = 1, ab = 2}, b = {ba = 3, bb = 5}, c = [1 2 4]}
如您所见,输出并不完美,因为c 使用逗号,但这应该很容易修复。我希望你明白这个想法,这就是你要找的。p>