This is the dictionary
cars = {\'A\':{\'speed\':70,
\'color\':2},
\'B\':{\'speed\':60,
\'color\':3}}
Using this
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
###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]
"""
# 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
for car,info in cars.items():
print(car)
for key,value in info.items():
print(key, ":", value)
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
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.