我写了一个Python函数来将字典转换为格式化字符串。我的目标是让函数接收一个字典作为输入,并将其转换为好看的字符串。例如,像
它非常好用。它检查字典项是否是另一个字典,如果是,则处理该字典,否则将其用作值。问题是:我不能在字典项中同时放置字典和字符串。例如,如果我想要:
{'text':'Hello', 'blah':{'hi':'hello','hello':'hi'}}
这样的东西会被转换成这样:
text: Hello blah: hi: hello hello: hi这是我写的代码:
indent = 0
def format_dict(d):
global indent
res = ""
for key in d:
res += (" " * indent) + key + ":\n"
if not type(d[key]) == type({}):
res += (" " * (indent + 1)) + d[key] + "\n"
else:
indent += 1
res += format_dict(d[key])
indent -= 1
return res
#test
print format_dict({'key with text content':'some text',
'key with dict content':
{'cheese': 'text', 'item':{'Blah': 'Hello'}}})
它非常好用。它检查字典项是否是另一个字典,如果是,则处理该字典,否则将其用作值。问题是:我不能在字典项中同时放置字典和字符串。例如,如果我想要:
blah: hi hello: hello again就没有办法做到。有没有办法在字典中拥有类似列表项的东西。像这样
{'blah':{'hi', 'hello':'hello again'}}
?如果您提供解决方案,能否告诉我需要如何更改我的代码(如果确实需要更改)。
注意:我正在使用python 2.5。