python - 如何在 Python 中很好地打印出字典?

标签 python

我刚刚开始学习 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/

相关文章:

python - 如何将内联(也许是 heredoc?)python 脚本插入 bash stdin/stdout 流管道

python - 如何在 IPython Notebook 3 中启用行号

python - 打破嵌套循环的缩进

python - Django 查询上的 value() 方法后的计数和最大值

python - 方面,并根据方面进行一些过滤

python - 消除一维阵列中的 Blob / Blob

python - 具有分类变量的 statsmodels 中的聚类标准误差 (Python)

python - 避免生成器分离器产生 None 值

Python:以 bool 值作为返回值的列表理解

java - 使用哪个平台可以实现最快的 Neo4j 图遍历?