Python字典格式

2024-05-19 20:12:19 发布

您现在位置: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


Tags: key函数字符串代码textformat内容hello
3条回答

为什么不直接使用yaml

import yaml
import StringIO

d = {'key with text content':'some text', 
     'key with dict content':
     {'cheese': 'text', 'item': {'Blah': 'Hello'}}}
s = StringIO.StringIO()
yaml.dump(d, s)
print s.getvalue()

打印出来:

key with dict content:
  cheese: text
  item: {Blah: Hello}
key with text content: some text

你可以把它装回录音机里

s.seek(0)
d = yaml.load(s)

你可以在字典里简单地存储一个列表。另外,最好不要使用全局来存储缩进。大致如下:

def format_value(v, indent):
    if isinstance(v, list):
         return ''.join([format_value(item, indent) for item in v])
    elif isinstance(v, dict):
         return format_dict(v, indent)
    elif isinstance(v, str):
         return ("   " * indent) + v + "\n"

def format_dict(d, indent=0):
    res = ""
    for key in d:
        res += ("   " * indent) + key + ":\n"
        res += format_value(d[key], indent + 1)
    return res

您可以将字典表示为具有子列表:

{'blah': [
    'hi',
    {'hello':[
        'hello again'
    ]},
    {'goodbye':[
        'hasta la vista, baby'
    ]}
]}

这样做的一个结果是,每个字典将只有一个键值对。从好的方面来说,这意味着可以有重复的键和确定的顺序,就像XML一样。

编辑:仔细想想,你可以把'hello''goodbye'折叠成一本字典,不过我个人会觉得这很混乱,因为你现在可能会有一堆杂乱有序的东西。所以我想每个字典的一键规则更多的是推荐而不是要求。

相关问题 更多 >