How to print a dictionary line by line in Python?

后端 未结 13 1292
情话喂你
情话喂你 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:18

    Modifying MrWonderful code

    import sys
    
    def print_dictionary(obj, ident):
        if type(obj) == dict:
            for k, v in obj.items():
                sys.stdout.write(ident)
                if hasattr(v, '__iter__'):
                    print k
                    print_dictionary(v, ident + '  ')
                else:
                    print '%s : %s' % (k, v)
        elif type(obj) == list:
            for v in obj:
                sys.stdout.write(ident)
                if hasattr(v, '__iter__'):
                    print_dictionary(v, ident + '  ')
                else:
                    print v
        else:
            print obj
    
    0 讨论(0)
  • 2020-11-28 02:20
    ###newbie exact answer desired (Python v3):
    ###=================================
    """
    cars = {'A':{'speed':70,
            'color':2},
            'B':{'speed':60,
            'color':3}}
    """
    
    for keys, values in  reversed(sorted(cars.items())):
        print(keys)
        for keys,values in sorted(values.items()):
            print(keys," : ", values)
    
    """
    Output:
    B
    color  :  3
    speed  :  60
    A
    color  :  2
    speed  :  70
    
    ##[Finished in 0.073s]
    """
    
    0 讨论(0)
  • 2020-11-28 02:23
    # Declare and Initialize Map
    map = {}
    
    map ["New"] = 1
    map ["to"] = 1
    map ["Python"] = 5
    map ["or"] = 2
    
    # Print Statement
    for i in map:
      print ("", i, ":", map[i])
    
    #  New : 1
    #  to : 1
    #  Python : 5
    #  or : 2
    
    0 讨论(0)
  • 2020-11-28 02:24
    for car,info in cars.items():
        print(car)
        for key,value in info.items():
            print(key, ":", value)
    
    0 讨论(0)
  • 2020-11-28 02:30

    Check the following one-liner:

    print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))
    

    Output:

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

    You could use the json module for this. The dumps function in this module converts a JSON object into a properly formatted string which you can then print.

    import json
    
    cars = {'A':{'speed':70, 'color':2},
            'B':{'speed':60, 'color':3}}
    
    print(json.dumps(cars, indent = 4))
    

    The output looks like

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

    The documentation also specifies a bunch of useful options for this method.

    0 讨论(0)
提交回复
热议问题