简体   繁体   English

如何在iPython中打印字典

[英]How to pretty print dictionaries in iPython

I'm currently using RethinkDB, which has a nice web UI with a Data Explorer which allows the user to print out the contents of the database like this: 我目前正在使用RethinkDB,它有一个很好的Web UI和一个Data Explorer,允许用户打印出数据库的内容,如下所示:

在此输入图像描述

Note that each key-value pair starts on a new line, and the keys and values (mostly) have different colors. 请注意,每个键值对都从一个新行开始,键和值(大多数)具有不同的颜色。 By contrast, if I print out the same using iPython, I get an almost illegible result: 相比之下,如果我使用iPython打印出相同的内容,我会得到一个几乎难以辨认的结果:

在此输入图像描述

This is slightly ameliorated if I iterate over the cursor and print each item, like so: 如果我迭代光标并print每个项目,这会略微改善,如下所示:

在此输入图像描述

However, this requires more typing and still doesn't look as good as the RethinkDB web UI. 但是,这需要更多的打字,但仍然不如RethinkDB Web UI。 Is there perhaps an iPython plugin that I can install to improve the appearance of the printed output? 是否可以安装一个iPython插件来改善打印输出的外观?

(I had a look at pprint , but this seems to control only the positioning of the text and not its color). (我看了一下pprint ,但这似乎只能控制文本的位置,而不是它的颜色)。

You could use json.dumps() : 你可以使用json.dumps()

import json 

for row in r.db(....).run(conn):
    print(json.dumps(row, indent=4))

Although this does not display the keys in sorted order, as appears to be the case in the example, it might be sufficient for your needs. 虽然这不按排序顺序显示键,但在示例中似乎是这样,但它可能足以满足您的需要。 As pointed out by @coder, you json.dumps() can sort the keys by specifying the sort_keys=True parameter. 正如@coder所指出的那样, json.dumps()可以通过指定sort_keys=True参数对键进行排序。

for row in r.db(....).run(conn):
    print(json.dumps(row, indent=4, sort_keys=True))

It might also be possible to print the object directly (haven't tested this): 也可以直接打印对象(尚未测试过):

print(json.dumps(r.db(....).run(conn), indent=4, sort_keys=True)

which might also print out the surrounding "list" object. 这也可能会打印出周围的“列表”对象。


To handle objects that do not support serialisation to JSON you can use a custom JSONEncoder . 要处理不支持序列化为JSON的对象,可以使用自定义JSONEncoder Here is an example which handles datetime.datetime objects: 这是一个处理datetime.datetime对象的示例:

from datetime import datetime

class DateTimeAwareJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            tz = obj.tzname()
            return obj.ctime() + (' {}'.format(tz) if tz else '')
        return super(DateTimeAwareJSONEncoder, self).default(obj)

for row in r.db(....).run(conn):
    print(json.dumps(row, indent=4, sort_keys=True, cls=DateTimeAwareJSONEncoder))

You can use datetime.strftime() to format the date time string as required. 您可以使用datetime.strftime()根据需要格式化日期时间字符串。

mhawke 's answer works if one adds the keyword argument time_format="raw" to RethinkDB's run() command. mhawke的答案工作如果加上关键字参数time_format="raw"来RethinkDB的run()命令。 (Otherwise, you get a TypeError because RethinkDB's object containing the time zone is not JSON serializable). (否则,您会收到TypeError因为包含时区的RethinkDB对象不是JSON可序列化的)。 The result looks like this: 结果如下:

在此输入图像描述

which is much more legible. 这更容易辨认。 A slight drawback is that the epoch_time is more difficult to interpret than the original time format. 一个小缺点是epoch_time比原始时间格式更难解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM