python 漂亮打印出一本字典。这是Al Sweigart的“Automate the Boring Stuff with Python”一书的修改版本。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 漂亮打印出一本字典。这是Al Sweigart的“Automate the Boring Stuff with Python”一书的修改版本。相关的知识,希望对你有一定的参考价值。
#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)
以上是关于python 漂亮打印出一本字典。这是Al Sweigart的“Automate the Boring Stuff with Python”一书的修改版本。的主要内容,如果未能解决你的问题,请参考以下文章