Python字典格式

标签 python formatting printing dictionary

我编写了一个 Python 函数来将字典转换为格式化字符串。我的目标是让一个函数接受字典作为输入并将其转换为看起来不错的字符串。例如,{'text':'Hello', 'blah':{'hi':'hello','hello':'hi'}} 会变成这样:

text:
    Hello
blah:
    hi:
        hello
    hello:
        hi

This is the code I wrote:

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

最佳答案

您可以简单地在字典中存储一个列表。另外,最好不要使用全局来存储缩进。类似的东西:

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

关于Python字典格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748378/

相关文章:

python - 获取行中每个值的最常见值 - pandas df

python - 将 pyparsing 结果与节点链表相关联的模式

python - 匹配除某些单词之外的所有字符

java - 从文件中打印出正确的数据

c - 如何用 C 语言为 HengSTLer C51 热敏票据打印机编程

css - 用于打印的分页代码

python - Linux 上 Python 的灵活 IPC 解决方案?

string - 我应该使用%s还是%v格式化错误

php - 在 linux 控制台中返回一行?

numpy - f numpy 数组的字符串格式