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

我刚刚开始学习 Python,我正在构建一个文本游戏。我想要一个库存系统,但我似乎不能打印出来的字典,它看起来难看。

This is what I have so far:

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])
179897 次浏览

下面是我要使用的一行程序(Edit: 适用于不可 JSON 序列化的内容)

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

Explanation: This iterates through the keys and values of the dictionary, creating a formatted string like key + tab + value for each. And "\n".join(... puts newlines between all those strings, forming a new string.

例如:

>>> 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])))

我最喜欢的方式:

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

同意,“很好”是非常主观的。看看这是否有帮助,我一直用来调试结果

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

我喜欢 Python 中包含的 pprint模块(漂亮的打印)。它既可以用来打印对象,也可以用来格式化对象的漂亮字符串版本。

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)

我编写这个函数是为了打印简单的字典:

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

我建议用 炸弹代替打印机。

例子:

印刷品

{'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中) :

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'}))