如何在Python中很好地打印出一本字典?

Rap*_*ang 32 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])
Run Code Online (Sandbox Code Playgroud)

谢谢!

fos*_*ock 41

我喜欢pprintPython中包含的模块.它可用于打印对象,或格式化它的漂亮字符串版本.

import pprint

# Prints the nicely formatted dictionary
pprint.pprint(dictionary)

# Sets 'pretty_dict_str' to 
pretty_dict_str = pprint.pformat(dictionary)
Run Code Online (Sandbox Code Playgroud)

但这听起来像是在打印出一个库存,用户可能希望将其显示为更像以下内容:

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)
Run Code Online (Sandbox Code Playgroud)

打印:

Items held:
shovels (3)
sticks (2)
dogs (1)
Run Code Online (Sandbox Code Playgroud)

  • 或`from pprint import pprint; pprint(dictionary)`... +1 (2认同)

Ofe*_*dan 23

我最喜欢的方式:

import json
print(json.dumps(dictionary, indent=4, sort_keys=True))
Run Code Online (Sandbox Code Playgroud)

  • @sudo你可以使用`default = str`所以如果某些东西不是JSON可序列化的,它首先被转换为字符串 (4认同)
  • 您的字典必须只包含JSON可序列化的对象,这些对象是字符串,各种数字和布尔值,以便工作.如果是这种情况,这是最简单的格式化最简单的方法. (3认同)
  • 请注意,如果存在不同类型的键(例如整数和字符串键),“sort_keys=True”会引发错误。 (2认同)

sud*_*udo 8

这是我要用的一线纸。(编辑:也适用于无法JSON序列化的内容)

print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
Run Code Online (Sandbox Code Playgroud)

说明:这将遍历字典的键和值,为每个键和键创建一个格式化的字符串,例如key + tab + value。并"\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
>>>
Run Code Online (Sandbox Code Playgroud)


dta*_*tar 5

我建议使用beeprint而不是 pprint。

例子:

打印

{'entities': {'hashtags': [],
              'urls': [{'display_url': 'github.com/panyanyany/beeprint',
                        'indices': [107, 126],
                        'url': 'https://github.com/panyanyany/beeprint'}],
              'user_mentions': []}}
Run Code Online (Sandbox Code Playgroud)

蜂印

{
  'entities': {
    'hashtags': [],
    'urls': [
      {
        'display_url': 'github.com/panyanyany/beeprint',
        'indices': [107, 126],
        'url': 'https://github.com/panyanyany/beeprint'}],
      },
    ],
    'user_mentions': [],
  },
}
Run Code Online (Sandbox Code Playgroud)