python字典格式要求_Python字典格式

我做了一个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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值