我刚刚开始学习 python,我正在构建一个文本游戏。我想要一个库存系统,但如果它看起来很丑,我似乎无法打印出字典。
这是我目前所拥有的:
def inventory():
for numberofitems in len(inventory_content.keys()):
inventory_things = list(inventory_content.keys())
inventory_amounts = list(inventory_content.values())
print(inventory_things[numberofitems])
最佳答案
我喜欢 pprint
Python 中包含的模块(Pretty Print)。它可以用来打印对象,或者格式化它的一个漂亮的字符串版本。
import pprint
# Prints the nicely formatted dictionary
pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)
但听起来您正在打印一份 list ,用户可能希望将其显示为更像以下内容:
def print_inventory(dct):
print("Items held:")
for item, amount in dct.items(): # dct.iteritems() in Python 2
print("{} ({})".format(item, amount))
inventory = {
"shovels": 3,
"sticks": 2,
"dogs": 1,
}
print_inventory(inventory)
哪个打印:
Items held:
shovels (3)
sticks (2)
dogs (1)
关于python - 如何在 Python 中很好地打印出字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689546/