如何在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])
我喜欢

Python中包含的pprint模块(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)

但听起来您正在打印一个清单,用户可能希望将其显示为以下内容:

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)

我最喜欢的方式:

import json
print(json.dumps(dictionary, indent=4, sort_keys=True))
这是我

将使用的单行代码。(编辑:也适用于无法 JSON 序列化的内容(

print("n".join("{}t{}".format(k, v) for k, v in dictionary.items()))

说明:这将遍历字典的键和值,为每个键和值创建一个格式化字符串,如键 + 制表符 + 值。"n".join(...在所有这些字符串之间放置换行符,形成一个新字符串。

例:

>>> dictionary = {1: 2, 4: 5, "foo": "bar"}
>>> print("n".join("{}t{}".format(k, v) for k, v in dictionary.items()))
1   2
4   5
foo bar
>>>

编辑2:这是一个排序版本。

"n".join("{}t{}".format(k, v) for k, v in sorted(dictionary.items(), key=lambda t: str(t[0])))

我建议使用beeprint而不是pprint。

例子:

印本

{'entities': {'hashtags': [],
              'urls': [{'display_url': 'github.com/panyanyany/beeprint',
                        'indices': [107, 126],
                        'url': 'https://github.com/panyanyany/beeprint'}],
              'user_mentions': []}}

蜂纹

{
  'entities': {
    'hashtags': [],
    'urls': [
      {
        'display_url': 'github.com/panyanyany/beeprint',
        'indices': [107, 126],
        'url': 'https://github.com/panyanyany/beeprint'}],
      },
    ],
    'user_mentions': [],
  },
}

Yaml 通常更具可读性,特别是如果您有复杂的嵌套对象、层次结构、嵌套字典等:

首先确保你有pyyaml模块:

pip install pyyaml

然后

import yaml
print(yaml.dump(my_dict))

从 Python 3.6 开始,您可以使用 f 字符串来编写 @sudo 的单行代码,甚至更紧凑

print("n".join(f"{k}t{v}" for k, v in dictionary.items()))

我写了这个函数来打印简单的字典:

def dictToString(dict):
  return str(dict).replace(', ','rn').replace("u'","").replace("'","")[1:-1]

同意,"nicely"是非常主观的。看看这是否有帮助,我一直用它来调试字典

for i in inventory_things.keys():
    logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i]))

我确实创建了函数(在Python 3中(:

def print_dict(dict):
    print(
    str(dict)
    .replace(', ', 'n')
    .replace(': ', ':t')
    .replace('{', '')
    .replace('}', '')
    )

也许它不适合所有需求,但我刚刚尝试了这个,它得到了一个很好的格式化输出因此,只需将字典转换为数据帧,即可

pd.DataFrame(your_dic.items())

您还可以定义列以进一步提高可读性

pd.DataFrame(your_dic.items(),columns={'Value','key'})

所以试一试:

print(pd.DataFrame(your_dic.items(),columns={'Value','key'}))

最新更新