我做了一个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'}}?如果你能提供一个解决方案,你能告诉我如何更改我的代码(如果它确实需要更改的话)。
注意:我正在使用Python2.5