b1nary0mega
5/10/2017 - 1:43 PM

Pretty print out a dictionary. This is a modified version from "Automate the Boring Stuff with Python" book by Al Sweigart.

Pretty print out a dictionary. This is a modified version from "Automate the Boring Stuff with Python" book by Al Sweigart.

#Pretty print out a given dictionary
def prettyPrint(tableName, itemsDict, leftWidth, rightWidth):
    print(tableName.center(leftWidth + rightWidth, '-'))
    for k, v in itemsDict.items():
        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth,))

#Create a dictionary to test with
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000, 'juice boxes': 6}

#The below will figure out what to use for spacing
longestKey = 0
longestValue = 0
for k, v in picnicItems.items():
    if len(k) > longestKey:
        longestKey = len(k)
    if len(str(v)) > longestValue:
        longestValue = len(str(v))
        
#Print out the dictionary, adding in a minimum gap size
minGap = 3
prettyPrint('PICNIC ITEMS', picnicItems, longestKey + minGap, longestValue + minGap)