I made a Python function to convert dictionaries to formatted strings. My goal was to get a function to 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'}}will be converted to 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
print format_dict({'key with text content':'some text',
'key with dict content':
{'cheese': 'text', 'item':{'Blah': 'Hello'}}})
It works great. It checks if the dictionary element is another dictionary, in which case it processes it or something else, then it will use it as a value. The problem is that I cannot have a dictionary and a string together in a dictionary element. For example, if I wanted to:
blah:
hi
hello:
hello again
. - , - . {'blah':{'hi', 'hello':'hello again'}}? , , ( ).
: Python 2.5