有什么方法可以正确打印有序的字典吗?

时间:2022-12-31 18:06:26

I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window.

我喜欢Python中的pprint模块。我经常使用它进行测试和调试。我经常使用width选项来确保输出在我的终端窗口内能够很好地匹配。

It has worked fine until they added the new ordered dictionary type in Python 2.7 (another cool feature I really like). If I try to pretty-print an ordered dictionary, it doesn't show nicely. Instead of having each key-value pair on its own line, the whole thing shows up on one long line, which wraps many times and is hard to read.

直到他们在Python 2.7中添加了新的有序字典类型(我非常喜欢的另一个很酷的特性),它才开始正常工作。如果我试着打印一个有序的字典,它不会显示得很好。不是每个键值对都在自己的线上,而是在一条长线上出现,这条线包裹了很多次,很难读懂。

Does anyone here have a way to make it print nicely, like the old unordered dictionaries? I could probably figure something out, possibly using the PrettyPrinter.format method, if I spend enough time, but I am wondering if anyone here already knows of a solution.

这里有人有办法让它像旧的无序字典一样顺利打印吗?我可能会想出来,可能是用了打印机。格式化方法,如果我花足够的时间,但是我想知道这里是否有人已经知道一个解决方案。

UPDATE: I filed a bug report for this. You can see it at http://bugs.python.org/issue10592.

更新:我为此提交了一个错误报告。您可以在http://bugs.python.org/e10592看到它。

11 个解决方案

#1


107  

As a temporary workaround you can try dumping in JSON format. You lose some type information, but it looks nice and keeps the order.

作为临时工作,您可以尝试以JSON格式进行转储。你丢失了一些类型的信息,但是它看起来很好并且保持了顺序。

import json

pprint(data, indent=4)
# ^ugly

print(json.dumps(data, indent=4))
# ^nice

#2


11  

The following will work if the order of your OrderedDict is an alpha sort, since pprint will sort a dict before print.

如果您的OrderedDict的排序是一个alpha排序,那么下面的操作将会工作,因为pprint将在打印之前对命令进行排序。

pprint(dict(o.items()))

#3


8  

Here's another answer that works by overriding and using the stock pprint() function internally. Unlike my earlier one it will handle OrderedDict's inside another container such as a list and should also be able to handle any optional keyword arguments given — however it does not have the same degree of control over the output that the other one afforded.

下面是通过在内部重写和使用stock pprint()函数来工作的另一个答案。与我之前的版本不同,它将在另一个容器(如列表)中处理OrderedDict's,并且应该能够处理给定的任何可选关键字参数——但是它对输出的控制程度不如另一个容器。

It operates by redirecting the stock function's output into a temporary buffer and then word wraps that before sending it on to the output stream. While the final output produced isn't exceptionalily pretty, it's decent and may be "good enough" to use as a workaround.

它的操作方法是将stock函数的输出重定向到一个临时缓冲区,然后word在将其发送到输出流之前对其进行包装。虽然最终生成的输出并不特别漂亮,但它还算不错,而且可能“足够好”,可以作为解决方案使用。

Update 2.0

更新2.0

Simplified by using standard library textwrap module, and modified to work in both Python 2 & 3.

通过使用标准库textwrap模块进行简化,并将其修改为适用于Python 2和3。

from collections import OrderedDict
try:
    from cStringIO import StringIO
except ImportError:  # Python 3
    from io import StringIO
from pprint import pprint as pp_pprint
import sys
import textwrap

def pprint(object, **kwrds):
    try:
        width = kwrds['width']
    except KeyError: # unlimited, use stock function
        pp_pprint(object, **kwrds)
        return
    buffer = StringIO()
    stream = kwrds.get('stream', sys.stdout)
    kwrds.update({'stream': buffer})
    pp_pprint(object, **kwrds)
    words = buffer.getvalue().split()
    buffer.close()

    # word wrap output onto multiple lines <= width characters
    try:
        print >> stream, textwrap.fill(' '.join(words), width=width)
    except TypeError:  # Python 3
        print(textwrap.fill(' '.join(words), width=width), file=stream)

d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
lod = [OrderedDict((('john',1), ('paul',2), ('mary',3))),
       OrderedDict((('moe',1), ('curly',2), ('larry',3))),
       OrderedDict((('weapons',1), ('mass',2), ('destruction',3)))]

Sample output:

样例输出:

pprint(d, width=40)

»   {'john': 1, 'mary': 3, 'paul': 2}

{'john': 1, 'mary': 3, 'paul': 2}

pprint(od, width=40)

» OrderedDict([('john', 1), ('paul', 2),
   ('mary', 3)])

»OrderedDict([(“约翰”,1),(“保罗”,2),(“玛丽”,3)))

pprint(lod, width=40)

» [OrderedDict([('john', 1), ('paul', 2),
   ('mary', 3)]), OrderedDict([('moe', 1),
   ('curly', 2), ('larry', 3)]),
   OrderedDict([('weapons', 1), ('mass',
   2), ('destruction', 3)])]

»[OrderedDict(((“约翰”,1),(“保罗”,2),(“玛丽”,3)]),OrderedDict(((“萌”,1),(‘花’,2),(“拉里”,3)]),OrderedDict(((“武器”,1),(‘质量’,2),(‘毁灭’,3))))

#4


7  

To print an ordered dict, e.g.

打印命令,打印命令,如

from collections import OrderedDict

d=OrderedDict([
    ('a', OrderedDict([
        ('a1',1),
        ('a2','sss')
    ])),
    ('b', OrderedDict([
        ('b1', OrderedDict([
            ('bb1',1),
            ('bb2',4.5)])),
        ('b2',4.5)
    ])),
])

I do

我做

def dict_or_OrdDict_to_formatted_str(OD, mode='dict', s="", indent=' '*4, level=0):
    def is_number(s):
        try:
            float(s)
            return True
        except ValueError:
            return False
    def fstr(s):
        return s if is_number(s) else '"%s"'%s
    if mode != 'dict':
        kv_tpl = '("%s", %s)'
        ST = 'OrderedDict([\n'; END = '])'
    else:
        kv_tpl = '"%s": %s'
        ST = '{\n'; END = '}'
    for i,k in enumerate(OD.keys()):
        if type(OD[k]) in [dict, OrderedDict]:
            level += 1
            s += (level-1)*indent+kv_tpl%(k,ST+dict_or_OrdDict_to_formatted_str(OD[k], mode=mode, indent=indent, level=level)+(level-1)*indent+END)
            level -= 1
        else:
            s += level*indent+kv_tpl%(k,fstr(OD[k]))
        if i!=len(OD)-1:
            s += ","
        s += "\n"
    return s

print dict_or_OrdDict_to_formatted_str(d)

Which yields

的收益率

"a": {
    "a1": 1,
    "a2": "sss"
},
"b": {
    "b1": {
        "bb1": 1,
        "bb2": 4.5
    },
    "b2": 4.5
}

or

print dict_or_OrdDict_to_formatted_str(d, mode='OD')

which yields

的收益率

("a", OrderedDict([
    ("a1", 1),
    ("a2", "sss")
])),
("b", OrderedDict([
    ("b1", OrderedDict([
        ("bb1", 1),
        ("bb2", 4.5)
    ])),
    ("b2", 4.5)
]))

#5


4  

Here’s a way that hacks the implementation of pprint. pprint sorts the keys before printing, so to preserve order, we just have to make the keys sort in the way we want.

这是一种破坏pprint实现的方法。pprint在打印前对键进行排序,所以为了保持顺序,我们只需要按我们想要的方式对键进行排序。

Note that this impacts the items() function. So you might want to preserve and restore the overridden functions after doing the pprint.

注意,这会影响items()函数。因此,您可能希望在执行pprint操作之后保存并恢复重写的函数。

from collections import OrderedDict
import pprint

class ItemKey(object):
  def __init__(self, name, position):
    self.name = name
    self.position = position
  def __cmp__(self, b):
    assert isinstance(b, ItemKey)
    return cmp(self.position, b.position)
  def __repr__(self):
    return repr(self.name)

OrderedDict.items = lambda self: [
    (ItemKey(name, i), value)
    for i, (name, value) in enumerate(self.iteritems())]
OrderedDict.__repr__ = dict.__repr__

a = OrderedDict()
a[4] = '4'
a[1] = '1'
a[2] = '2'
print pprint.pformat(a) # {4: '4', 1: '1', 2: '2'}

#6


2  

This is pretty crude, but I just needed a way to visualize a data structure made up of any arbitrary Mappings and Iterables and this is what I came up with before giving up. It's recursive, so it will fall through nested structures and lists just fine. I used the Mapping and Iterable abstract base classes from collections to handle just about anything.

这很粗糙,但我只是需要一种方法来可视化由任意映射和可迭代组成的数据结构,这是我在放弃之前想到的。它是递归的,所以它会通过嵌套结构和列表。我使用集合中的映射和可迭代的抽象基类来处理任何事情。

I was aiming for almost yaml like output with concise python code, but didn't quite make it.

我的目标是用简洁的python代码实现几乎像yaml一样的输出,但没有成功。

def format_structure(d, level=0):
    x = ""
    if isinstance(d, Mapping):
        lenk = max(map(lambda x: len(str(x)), d.keys()))
        for k, v in d.items():
            key_text = "\n" + " "*level + " "*(lenk - len(str(k))) + str(k)
            x += key_text + ": " + format_structure(v, level=level+lenk)
    elif isinstance(d, Iterable) and not isinstance(d, basestring):
        for e in d:
            x += "\n" + " "*level + "- " + format_structure(e, level=level+4)
    else:
        x = str(d)
    return x

and some test data using OrderedDict and lists of OrderedDicts... (sheesh Python needs OrderedDict literals sooo badly...)

还有一些使用OrderedDict和OrderedDicts列表的测试数据……(sheesh Python需要OrderedDict literals sooo不好…)

d = OrderedDict([("main",
                  OrderedDict([("window",
                                OrderedDict([("size", [500, 500]),
                                             ("position", [100, 900])])),
                               ("splash_enabled", True),
                               ("theme", "Dark")])),
                 ("updates",
                  OrderedDict([("automatic", True),
                               ("servers",
                                [OrderedDict([("url", "http://server1.com"),
                                              ("name", "Stable")]),
                                 OrderedDict([("url", "http://server2.com"),
                                              ("name", "Beta")]),
                                 OrderedDict([("url", "http://server3.com"),
                                              ("name", "Dev")])]),
                               ("prompt_restart", True)])),
                 ("logging",
                  OrderedDict([("enabled", True),
                               ("rotate", True)]))])

print format_structure(d)

yields the following output:

产生以下输出:

   main: 
               window: 
                         size: 
                             - 500
                             - 500
                     position: 
                             - 100
                             - 900
       splash_enabled: True
                theme: Dark
updates: 
            automatic: True
              servers: 
                     - 
                          url: http://server1.com
                         name: Stable
                     - 
                          url: http://server2.com
                         name: Beta
                     - 
                          url: http://server3.com
                         name: Dev
       prompt_restart: True
logging: 
       enabled: True
        rotate: True

I had some thoughts along the way of using str.format() for better alignment, but didn't feel like digging into it. You'd need to dynamically specify the field widths depending on the type of alignment you want, which would get either tricky or cumbersome.

在使用string .format()进行更好的对齐的过程中,我有一些想法,但我不想深入研究它。您需要根据需要的对齐类型动态地指定字段宽度,这可能比较棘手,也可能比较麻烦。

Anyway, this shows me my data in readable hierarchical fashion, so that works for me!

无论如何,这显示了我的数据以可读的分层方式,所以这对我有用!

#7


2  

def pprint_od(od):
    print "{"
    for key in od:
        print "%s:%s,\n" % (key, od[key]) # Fixed syntax
    print "}"

There you go ^^

好了^ ^

for item in li:
    pprint_od(item)

or

(pprint_od(item) for item in li)

#8


1  

The pprint() method is just invoking the __repr__() method of things in it, and OrderedDict doesn't appear to do much in it's method (or doesn't have one or something).

pprint()方法只是调用它的__repr__()方法,而OrderedDict在它的方法中似乎没有什么作用(或者没有一个或其他的方法)。

Here's a cheap solution that should work IF YOU DON'T CARE ABOUT THE ORDER BEING VISIBLE IN THE PPRINT OUTPUT, which may be a big if:

如果您不关心PPRINT输出中可见的顺序,那么这里有一个廉价的解决方案,这可能是一个很大的假设:

class PrintableOrderedDict(OrderedDict):
    def __repr__(self):
        return dict.__repr__(self)

I'm actually surprised that the order isn't preserved... ah well.

我很惊讶订单没有保存……啊。

#9


0  

You could redefine pprint() and intercept calls for OrderedDict's. Here's a simple illustration. As written, the OrderedDict override code ignores any optional stream, indent, width, or depth keywords that may have been passed, but could be enhanced to implement them. Unfortunately this technique doesn't handle them inside another container, such as a list of OrderDict's

您可以重新定义pprint(),并截取OrderedDict的调用。这是一个简单的例子。如前所述,OrderedDict重写代码忽略任何可选的流、缩进、宽度或深度关键字,这些关键字可能已经被传递,但可以进行增强以实现它们。不幸的是,这种技术不能在另一个容器中处理它们,比如OrderDict的列表

from collections import OrderedDict
from pprint import pprint as pp_pprint

def pprint(obj, *args, **kwrds):
    if not isinstance(obj, OrderedDict):
        # use stock function
        return pp_pprint(obj, *args, **kwrds)
    else:
        # very simple sample custom implementation...
        print "{"
        for key in obj:
            print "    %r:%r" % (key, obj[key])
        print "}"

l = [10, 2, 4]
d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
pprint(l, width=4)
# [10,
#  2,
#  4]
pprint(d)
# {'john': 1, 'mary': 3, 'paul': 2}

pprint(od)
# {
#     'john':1
#     'paul':2
#     'mary':3
# }

#10


0  

If the dictionary items are all of one type, you could use the amazing data-handling library pandas:

如果字典条目都是一种类型,你可以使用令人惊叹的数据处理图书馆熊猫:

>>> import pandas as pd
>>> x = {'foo':1, 'bar':2}
>>> pd.Series(x)
bar    2
foo    1
dtype: int64

or

>>> import pandas as pd
>>> x = {'foo':'bar', 'baz':'bam'}
>>> pd.Series(x)
baz    bam
foo    bar
dtype: object

#11


0  

You can also use this simplification of the kzh answer:

你也可以用这个简化的kzh答案:

pprint(data.items(), indent=4)

It preserves the order and will output almost the same than the webwurst answer (print through json dump).

它保留了顺序,并将输出几乎与webwurst答案相同的结果(通过json转储打印)。

#1


107  

As a temporary workaround you can try dumping in JSON format. You lose some type information, but it looks nice and keeps the order.

作为临时工作,您可以尝试以JSON格式进行转储。你丢失了一些类型的信息,但是它看起来很好并且保持了顺序。

import json

pprint(data, indent=4)
# ^ugly

print(json.dumps(data, indent=4))
# ^nice

#2


11  

The following will work if the order of your OrderedDict is an alpha sort, since pprint will sort a dict before print.

如果您的OrderedDict的排序是一个alpha排序,那么下面的操作将会工作,因为pprint将在打印之前对命令进行排序。

pprint(dict(o.items()))

#3


8  

Here's another answer that works by overriding and using the stock pprint() function internally. Unlike my earlier one it will handle OrderedDict's inside another container such as a list and should also be able to handle any optional keyword arguments given — however it does not have the same degree of control over the output that the other one afforded.

下面是通过在内部重写和使用stock pprint()函数来工作的另一个答案。与我之前的版本不同,它将在另一个容器(如列表)中处理OrderedDict's,并且应该能够处理给定的任何可选关键字参数——但是它对输出的控制程度不如另一个容器。

It operates by redirecting the stock function's output into a temporary buffer and then word wraps that before sending it on to the output stream. While the final output produced isn't exceptionalily pretty, it's decent and may be "good enough" to use as a workaround.

它的操作方法是将stock函数的输出重定向到一个临时缓冲区,然后word在将其发送到输出流之前对其进行包装。虽然最终生成的输出并不特别漂亮,但它还算不错,而且可能“足够好”,可以作为解决方案使用。

Update 2.0

更新2.0

Simplified by using standard library textwrap module, and modified to work in both Python 2 & 3.

通过使用标准库textwrap模块进行简化,并将其修改为适用于Python 2和3。

from collections import OrderedDict
try:
    from cStringIO import StringIO
except ImportError:  # Python 3
    from io import StringIO
from pprint import pprint as pp_pprint
import sys
import textwrap

def pprint(object, **kwrds):
    try:
        width = kwrds['width']
    except KeyError: # unlimited, use stock function
        pp_pprint(object, **kwrds)
        return
    buffer = StringIO()
    stream = kwrds.get('stream', sys.stdout)
    kwrds.update({'stream': buffer})
    pp_pprint(object, **kwrds)
    words = buffer.getvalue().split()
    buffer.close()

    # word wrap output onto multiple lines <= width characters
    try:
        print >> stream, textwrap.fill(' '.join(words), width=width)
    except TypeError:  # Python 3
        print(textwrap.fill(' '.join(words), width=width), file=stream)

d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
lod = [OrderedDict((('john',1), ('paul',2), ('mary',3))),
       OrderedDict((('moe',1), ('curly',2), ('larry',3))),
       OrderedDict((('weapons',1), ('mass',2), ('destruction',3)))]

Sample output:

样例输出:

pprint(d, width=40)

»   {'john': 1, 'mary': 3, 'paul': 2}

{'john': 1, 'mary': 3, 'paul': 2}

pprint(od, width=40)

» OrderedDict([('john', 1), ('paul', 2),
   ('mary', 3)])

»OrderedDict([(“约翰”,1),(“保罗”,2),(“玛丽”,3)))

pprint(lod, width=40)

» [OrderedDict([('john', 1), ('paul', 2),
   ('mary', 3)]), OrderedDict([('moe', 1),
   ('curly', 2), ('larry', 3)]),
   OrderedDict([('weapons', 1), ('mass',
   2), ('destruction', 3)])]

»[OrderedDict(((“约翰”,1),(“保罗”,2),(“玛丽”,3)]),OrderedDict(((“萌”,1),(‘花’,2),(“拉里”,3)]),OrderedDict(((“武器”,1),(‘质量’,2),(‘毁灭’,3))))

#4


7  

To print an ordered dict, e.g.

打印命令,打印命令,如

from collections import OrderedDict

d=OrderedDict([
    ('a', OrderedDict([
        ('a1',1),
        ('a2','sss')
    ])),
    ('b', OrderedDict([
        ('b1', OrderedDict([
            ('bb1',1),
            ('bb2',4.5)])),
        ('b2',4.5)
    ])),
])

I do

我做

def dict_or_OrdDict_to_formatted_str(OD, mode='dict', s="", indent=' '*4, level=0):
    def is_number(s):
        try:
            float(s)
            return True
        except ValueError:
            return False
    def fstr(s):
        return s if is_number(s) else '"%s"'%s
    if mode != 'dict':
        kv_tpl = '("%s", %s)'
        ST = 'OrderedDict([\n'; END = '])'
    else:
        kv_tpl = '"%s": %s'
        ST = '{\n'; END = '}'
    for i,k in enumerate(OD.keys()):
        if type(OD[k]) in [dict, OrderedDict]:
            level += 1
            s += (level-1)*indent+kv_tpl%(k,ST+dict_or_OrdDict_to_formatted_str(OD[k], mode=mode, indent=indent, level=level)+(level-1)*indent+END)
            level -= 1
        else:
            s += level*indent+kv_tpl%(k,fstr(OD[k]))
        if i!=len(OD)-1:
            s += ","
        s += "\n"
    return s

print dict_or_OrdDict_to_formatted_str(d)

Which yields

的收益率

"a": {
    "a1": 1,
    "a2": "sss"
},
"b": {
    "b1": {
        "bb1": 1,
        "bb2": 4.5
    },
    "b2": 4.5
}

or

print dict_or_OrdDict_to_formatted_str(d, mode='OD')

which yields

的收益率

("a", OrderedDict([
    ("a1", 1),
    ("a2", "sss")
])),
("b", OrderedDict([
    ("b1", OrderedDict([
        ("bb1", 1),
        ("bb2", 4.5)
    ])),
    ("b2", 4.5)
]))

#5


4  

Here’s a way that hacks the implementation of pprint. pprint sorts the keys before printing, so to preserve order, we just have to make the keys sort in the way we want.

这是一种破坏pprint实现的方法。pprint在打印前对键进行排序,所以为了保持顺序,我们只需要按我们想要的方式对键进行排序。

Note that this impacts the items() function. So you might want to preserve and restore the overridden functions after doing the pprint.

注意,这会影响items()函数。因此,您可能希望在执行pprint操作之后保存并恢复重写的函数。

from collections import OrderedDict
import pprint

class ItemKey(object):
  def __init__(self, name, position):
    self.name = name
    self.position = position
  def __cmp__(self, b):
    assert isinstance(b, ItemKey)
    return cmp(self.position, b.position)
  def __repr__(self):
    return repr(self.name)

OrderedDict.items = lambda self: [
    (ItemKey(name, i), value)
    for i, (name, value) in enumerate(self.iteritems())]
OrderedDict.__repr__ = dict.__repr__

a = OrderedDict()
a[4] = '4'
a[1] = '1'
a[2] = '2'
print pprint.pformat(a) # {4: '4', 1: '1', 2: '2'}

#6


2  

This is pretty crude, but I just needed a way to visualize a data structure made up of any arbitrary Mappings and Iterables and this is what I came up with before giving up. It's recursive, so it will fall through nested structures and lists just fine. I used the Mapping and Iterable abstract base classes from collections to handle just about anything.

这很粗糙,但我只是需要一种方法来可视化由任意映射和可迭代组成的数据结构,这是我在放弃之前想到的。它是递归的,所以它会通过嵌套结构和列表。我使用集合中的映射和可迭代的抽象基类来处理任何事情。

I was aiming for almost yaml like output with concise python code, but didn't quite make it.

我的目标是用简洁的python代码实现几乎像yaml一样的输出,但没有成功。

def format_structure(d, level=0):
    x = ""
    if isinstance(d, Mapping):
        lenk = max(map(lambda x: len(str(x)), d.keys()))
        for k, v in d.items():
            key_text = "\n" + " "*level + " "*(lenk - len(str(k))) + str(k)
            x += key_text + ": " + format_structure(v, level=level+lenk)
    elif isinstance(d, Iterable) and not isinstance(d, basestring):
        for e in d:
            x += "\n" + " "*level + "- " + format_structure(e, level=level+4)
    else:
        x = str(d)
    return x

and some test data using OrderedDict and lists of OrderedDicts... (sheesh Python needs OrderedDict literals sooo badly...)

还有一些使用OrderedDict和OrderedDicts列表的测试数据……(sheesh Python需要OrderedDict literals sooo不好…)

d = OrderedDict([("main",
                  OrderedDict([("window",
                                OrderedDict([("size", [500, 500]),
                                             ("position", [100, 900])])),
                               ("splash_enabled", True),
                               ("theme", "Dark")])),
                 ("updates",
                  OrderedDict([("automatic", True),
                               ("servers",
                                [OrderedDict([("url", "http://server1.com"),
                                              ("name", "Stable")]),
                                 OrderedDict([("url", "http://server2.com"),
                                              ("name", "Beta")]),
                                 OrderedDict([("url", "http://server3.com"),
                                              ("name", "Dev")])]),
                               ("prompt_restart", True)])),
                 ("logging",
                  OrderedDict([("enabled", True),
                               ("rotate", True)]))])

print format_structure(d)

yields the following output:

产生以下输出:

   main: 
               window: 
                         size: 
                             - 500
                             - 500
                     position: 
                             - 100
                             - 900
       splash_enabled: True
                theme: Dark
updates: 
            automatic: True
              servers: 
                     - 
                          url: http://server1.com
                         name: Stable
                     - 
                          url: http://server2.com
                         name: Beta
                     - 
                          url: http://server3.com
                         name: Dev
       prompt_restart: True
logging: 
       enabled: True
        rotate: True

I had some thoughts along the way of using str.format() for better alignment, but didn't feel like digging into it. You'd need to dynamically specify the field widths depending on the type of alignment you want, which would get either tricky or cumbersome.

在使用string .format()进行更好的对齐的过程中,我有一些想法,但我不想深入研究它。您需要根据需要的对齐类型动态地指定字段宽度,这可能比较棘手,也可能比较麻烦。

Anyway, this shows me my data in readable hierarchical fashion, so that works for me!

无论如何,这显示了我的数据以可读的分层方式,所以这对我有用!

#7


2  

def pprint_od(od):
    print "{"
    for key in od:
        print "%s:%s,\n" % (key, od[key]) # Fixed syntax
    print "}"

There you go ^^

好了^ ^

for item in li:
    pprint_od(item)

or

(pprint_od(item) for item in li)

#8


1  

The pprint() method is just invoking the __repr__() method of things in it, and OrderedDict doesn't appear to do much in it's method (or doesn't have one or something).

pprint()方法只是调用它的__repr__()方法,而OrderedDict在它的方法中似乎没有什么作用(或者没有一个或其他的方法)。

Here's a cheap solution that should work IF YOU DON'T CARE ABOUT THE ORDER BEING VISIBLE IN THE PPRINT OUTPUT, which may be a big if:

如果您不关心PPRINT输出中可见的顺序,那么这里有一个廉价的解决方案,这可能是一个很大的假设:

class PrintableOrderedDict(OrderedDict):
    def __repr__(self):
        return dict.__repr__(self)

I'm actually surprised that the order isn't preserved... ah well.

我很惊讶订单没有保存……啊。

#9


0  

You could redefine pprint() and intercept calls for OrderedDict's. Here's a simple illustration. As written, the OrderedDict override code ignores any optional stream, indent, width, or depth keywords that may have been passed, but could be enhanced to implement them. Unfortunately this technique doesn't handle them inside another container, such as a list of OrderDict's

您可以重新定义pprint(),并截取OrderedDict的调用。这是一个简单的例子。如前所述,OrderedDict重写代码忽略任何可选的流、缩进、宽度或深度关键字,这些关键字可能已经被传递,但可以进行增强以实现它们。不幸的是,这种技术不能在另一个容器中处理它们,比如OrderDict的列表

from collections import OrderedDict
from pprint import pprint as pp_pprint

def pprint(obj, *args, **kwrds):
    if not isinstance(obj, OrderedDict):
        # use stock function
        return pp_pprint(obj, *args, **kwrds)
    else:
        # very simple sample custom implementation...
        print "{"
        for key in obj:
            print "    %r:%r" % (key, obj[key])
        print "}"

l = [10, 2, 4]
d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
pprint(l, width=4)
# [10,
#  2,
#  4]
pprint(d)
# {'john': 1, 'mary': 3, 'paul': 2}

pprint(od)
# {
#     'john':1
#     'paul':2
#     'mary':3
# }

#10


0  

If the dictionary items are all of one type, you could use the amazing data-handling library pandas:

如果字典条目都是一种类型,你可以使用令人惊叹的数据处理图书馆熊猫:

>>> import pandas as pd
>>> x = {'foo':1, 'bar':2}
>>> pd.Series(x)
bar    2
foo    1
dtype: int64

or

>>> import pandas as pd
>>> x = {'foo':'bar', 'baz':'bam'}
>>> pd.Series(x)
baz    bam
foo    bar
dtype: object

#11


0  

You can also use this simplification of the kzh answer:

你也可以用这个简化的kzh答案:

pprint(data.items(), indent=4)

It preserves the order and will output almost the same than the webwurst answer (print through json dump).

它保留了顺序,并将输出几乎与webwurst答案相同的结果(通过json转储打印)。