我做了一个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
为什么不直接使用yaml?
打印出来:
你可以把它装回录音机里
你可以在字典里简单地存储一个列表。另外,最好不要使用全局来存储缩进。大致如下:
您可以将字典表示为具有子列表:
这样做的一个结果是,每个字典将只有一个键值对。从好的方面来说,这意味着可以有重复的键和确定的顺序,就像XML一样。
编辑:仔细想想,你可以把
'hello'
和'goodbye'
折叠成一本字典,不过我个人会觉得这很混乱,因为你现在可能会有一堆杂乱有序的东西。所以我想每个字典的一键规则更多的是推荐而不是要求。相关问题 更多 >
编程相关推荐