Python dictionary formatting

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
#test
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

+4
6

. , . - :

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
+2

:

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

, -. , , , XML.

EDIT: , 'hello' 'goodbye' , , , , , , .

+2

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

dict

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

- , . , None. None if not type(d[key]) == type({}): continue, . , , if not isinstance(d[key], dict):.

0
source

As already mentioned, you need to use lists as values ​​when you want to have text and a dictionary on the same level. here is some code that prints what you need.

# -*- coding: utf-8 -*-
#!/usr/bin/env python2.5
# http://stackoverflow.com/questions/2748378/python-dictionary-formating

def pretty_dict(d, indent=0, spacer='.'):
    """
    takes a dict {'text':'Hello', 'blah':{'hi':'hello','hello':'hi'}}
    And prints:

    text:
        Hello
    blah:
        hi:
            hello
        hello:
            hi

    """
    kindent = spacer * indent

    if isinstance(d, basestring):
        return kindent + d

    if isinstance(d, list):
        return '\n'.join([(pretty_dict(v, indent, spacer)) for v in d])

    return '\n'.join(['%s%s:\n%s' % (kindent, k, pretty_dict(v, indent + 1, spacer)) 
        for k, v in d.items()])


test_a = {'text':'Hello', 'blah':{'hi':'hello','hello':'hi'}}
test_b = {'key with text content':'some text', 'key with dict content':
    {'cheese': 'text', 'item':{'Blah': 'Hello'}}}
test_c = {'blah':['hi', {'hello':'hello again'}]}
test_d = {'blah': [
    'hi',
    {'hello':[
        'hello again'
    ]},
    {'goodbye':[
        'hasta la vista, baby'
]}
]}


if __name__ == '__main__':
    print pretty_dict(test_a)
    print pretty_dict(test_b)
    print pretty_dict(test_c)
    print pretty_dict(test_d)
0
source

Why not use a beautiful print that already does all this?

http://docs.python.org/dev/library/pprint.html

0
source

Source: https://habr.com/ru/post/1743592/


All Articles