How to print a dictionary line by line in Python?

后端 未结 13 1295
情话喂你
情话喂你 2020-11-28 02:02

This is the dictionary

cars = {\'A\':{\'speed\':70,
        \'color\':2},
        \'B\':{\'speed\':60,
        \'color\':3}}

Using this

相关标签:
13条回答
  • 2020-11-28 02:32

    Here is my solution to the problem. I think it's similar in approach, but a little simpler than some of the other answers. It also allows for an arbitrary number of sub-dictionaries and seems to work for any datatype (I even tested it on a dictionary which had functions as values):

    def pprint(web, level):
        for k,v in web.items():
            if isinstance(v, dict):
                print('\t'*level, f'{k}: ')
                level += 1
                pprint(v, level)
                level -= 1
            else:
                print('\t'*level, k, ": ", v)
    
    0 讨论(0)
  • 2020-11-28 02:36
    for x in cars:
        print (x)
        for y in cars[x]:
            print (y,':',cars[x][y])
    

    output:

    A
    color : 2
    speed : 70
    B
    color : 3
    speed : 60
    
    0 讨论(0)
  • 2020-11-28 02:40

    A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:

    def dumpclean(obj):
        if isinstance(obj, dict):
            for k, v in obj.items():
                if hasattr(v, '__iter__'):
                    print k
                    dumpclean(v)
                else:
                    print '%s : %s' % (k, v)
        elif isinstance(obj, list):
            for v in obj:
                if hasattr(v, '__iter__'):
                    dumpclean(v)
                else:
                    print v
        else:
            print obj
    

    This produces the output:

    A
    color : 2
    speed : 70
    B
    color : 3
    speed : 60
    

    I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.

    import sys
    
    def dump(obj, nested_level=0, output=sys.stdout):
        spacing = '   '
        if isinstance(obj, dict):
            print >> output, '%s{' % ((nested_level) * spacing)
            for k, v in obj.items():
                if hasattr(v, '__iter__'):
                    print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
                    dump(v, nested_level + 1, output)
                else:
                    print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
            print >> output, '%s}' % (nested_level * spacing)
        elif isinstance(obj, list):
            print >> output, '%s[' % ((nested_level) * spacing)
            for v in obj:
                if hasattr(v, '__iter__'):
                    dump(v, nested_level + 1, output)
                else:
                    print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
            print >> output, '%s]' % ((nested_level) * spacing)
        else:
            print >> output, '%s%s' % (nested_level * spacing, obj)
    

    Using this function, the OP's output looks like this:

    {
       A:
       {
          color: 2
          speed: 70
       }
       B:
       {
          color: 3
          speed: 60
       }
    }
    

    which I personally found to be more useful and descriptive.

    Given the slightly less-trivial example of:

    {"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
    

    The OP's requested solution yields this:

    test
    1 : 3
    test3
    (1, 2)
    abc
    def
    ghi
    (4, 5) : def
    test2
    (1, 2)
    (3, 4)
    

    whereas the 'enhanced' version yields this:

    {
       test:
       [
          {
             1: 3
          }
       ]
       test3:
       {
          (1, 2):
          [
             abc
             def
             ghi
          ]
          (4, 5): def
       }
       test2:
       [
          (1, 2)
          (3, 4)
       ]
    }
    

    I hope this provides some value to the next person looking for this type of functionality.

    0 讨论(0)
  • 2020-11-28 02:40

    You have a nested structure, so you need to format the nested dictionary too:

    for key, car in cars.items():
        print(key)
        for attribute, value in car.items():
            print('{} : {}'.format(attribute, value))
    

    This prints:

    A
    color : 2
    speed : 70
    B
    color : 3
    speed : 60
    
    0 讨论(0)
  • 2020-11-28 02:40

    This will work if you know the tree only has two levels:

    for k1 in cars:
        print(k1)
        d = cars[k1]
        for k2 in d
            print(k2, ':', d[k2])
    
    0 讨论(0)
  • 2020-11-28 02:42

    pprint.pprint() is a good tool for this job:

    >>> import pprint
    >>> cars = {'A':{'speed':70,
    ...         'color':2},
    ...         'B':{'speed':60,
    ...         'color':3}}
    >>> pprint.pprint(cars, width=1)
    {'A': {'color': 2,
           'speed': 70},
     'B': {'color': 3,
           'speed': 60}}
    
    0 讨论(0)
提交回复
热议问题