Python dictionary formating

Posted by None on Stack Overflow See other posts from Stack Overflow or by None
Published on 2010-05-01T00:26:23Z Indexed on 2010/05/01 0:37 UTC
Read the original article Hit count: 573

Filed under:
|
|
|

I made a python function to convert dictionaries to formatted strings. My goal was to have a function take a dictionary for input and turn it into a string that looked good. For example, something like "{'text':'Hello', 'blah':{'hi':'hello','hello':'hi'}}" would be turned into this:

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'}}})

It works like a charm. It checks if the dictionary item is another dictionary, in which it process that, or something else, in which it would use that as the value. The problem is: I can't have a dictionary and a string together in a dictionary item. For example: if I wanted

blah:
    hi
    hello:
        hello again

there'd be no way to do it. Is there some way I could have something like a list item in a dictionary. Something like this "{'blah':{'hi', 'hello':'hello again'}}"? And if you provide a solution could you tell me how I would need to change my code (if it did require changes).
Note: I am using python 2.5

© Stack Overflow or respective owner

Related posts about python

Related posts about dict