How to print a dictionary line by line in Python?

This is a dictionary

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

Using this for loop

 for keys,values in cars.items(): print(keys) print(values) 

He prints the following:

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

But I want the program to print it like this:

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

I just started to learn dictionaries, so I'm not sure how to do this.

+142
python dictionary printing
Apr 03 '13 at 11:10
source share
11 answers
 for x in cars: print (x) for y in cars[x]: print (y,':',cars[x][y]) 

exit:

 A color : 2 speed : 70 B color : 3 speed : 60 
+125
Apr 03 '13 at 11:14
source share

You can use the json module for this. The dumps function in this module converts a JSON object into a properly formatted string that you can 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 indicates a bunch of useful parameters for this method.

+93
Dec 16 '15 at 7:59
source share

A more generalized solution that processes arbitrarily deeply nested dictations and lists:

 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 conclusion:

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

I ran into a similar need and developed a more robust feature for myself. I include this here, in case this may matter to another. While checking the nose, I also found it useful 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 output is as follows:

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

which I personally found more useful and descriptive.

Given a slightly less trivial example:

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

The requested OP solution gives this:

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

whereas the "improved" version gives the following:

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

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

+83
Jan 10 '14 at 16:10
source share

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

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

Fingerprints:

 A color : 2 speed : 70 B color : 3 speed : 60 
+29
Apr 03 '13 at 11:13
source share

As Martin Pieter mentioned in one of the comments above, PrettyPrint 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}} 
+21
Sep 13 '15 at 11:50
source share
 for car,info in cars.items(): print(car) for key,value in info.items(): print(key, ":", value) 
+7
Apr 03 '13 at 11:13
source share

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

 for k1 in cars: print(k1) d = cars[k1] for k2 in d print(k2, ':', d[k2]) 
+5
Apr 03 '13 at 11:15
source share

Check the following single line image:

 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 
+4
Jul 27 '15 at 21:07
source share
 ###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
Feb 12 '19 at 23:11
source share
 # 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
Apr 24 '19 at 6:12
source share

Change 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 
-one
Mar 29 '16 at 1:12
source share



All Articles