如何在 Python 中很好地打印字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44689546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print out a dictionary nicely in Python?
提问by Raphael Huang
I've just started to learn python and I'm building a text game. I want an inventory system, but I can't seem to print out the dictionary without it looking ugly.
我刚刚开始学习 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])
回答by foslock
I like the pprint
module included in Python. It can be used to either print the object, or format a nice string version of it.
我喜欢pprint
Python 中包含的模块。它可用于打印对象,或格式化它的漂亮字符串版本。
import pprint
# Prints the nicely formatted dictionary
pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to
pretty_dict_str = pprint.pformat(dictionary)
But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:
但听起来您正在打印一份清单,用户可能希望将其显示为更类似于以下内容:
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)
which prints:
打印:
Items held:
shovels (3)
sticks (2)
dogs (1)
回答by Ofer Sadan
My favorite way:
我最喜欢的方式:
import json
print(json.dumps(dictionary, indent=4, sort_keys=True))
回答by sudo
Here's the one-liner I'd use. (Edit: works for things that aren't JSON-serializable too)
这是我会使用的单线。(编辑:也适用于不可 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.
说明:这将遍历字典的键和值,为每个键创建一个格式化的字符串,如键 + 制表符 + 值。并"\n".join(...
在所有这些字符串之间放置换行符,形成一个新字符串。
Example:
例子:
>>> 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
>>>
回答by dtar
I would suggest to use beeprintinstead of pprint.
我建议使用beeprint而不是 pprint。
Examples:
例子:
pprint
打印
{'entities': {'hashtags': [],
'urls': [{'display_url': 'github.com/panyanyany/beeprint',
'indices': [107, 126],
'url': 'https://github.com/panyanyany/beeprint'}],
'user_mentions': []}}
beeprint
蜂印
{
'entities': {
'hashtags': [],
'urls': [
{
'display_url': 'github.com/panyanyany/beeprint',
'indices': [107, 126],
'url': 'https://github.com/panyanyany/beeprint'}],
},
],
'user_mentions': [],
},
}
回答by Shital Shah
Yaml is typically much more readable, especially if you have complicated nested objects, hierarchies, nested dictionaries etc:
Yaml 通常更具可读性,尤其是当您有复杂的嵌套对象、层次结构、嵌套字典等时:
First make sure you have pyyaml module:
首先确保你有 pyyaml 模块:
pip install pyyaml
Then,
然后,
import yaml
print(yaml.dump(my_dict))
回答by Nautilus
I wrote this function to print simple dictionaries:
我写了这个函数来打印简单的字典:
def dictToString(dict):
return str(dict).replace(', ','\r\n').replace("u'","").replace("'","")[1:-1]
回答by Balaji Narayanaswamy
Agree, "nicely" is very subjective. See if this helps, which I have been using to debug dict
同意,“很好”是非常主观的。看看这是否有帮助,我一直在用它来调试 dict
for i in inventory_things.keys():
logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i]))