开发者

Why does pprint module sorts dict keys differently from print?

pprint sorts dicts keys alphabet开发者_如何转开发ically, print sorts them in default order.

from pprint import pprint
d = {'foo': 1, 'bar': 2, 'baz': 3}

pprint(d)
# {'bar': 2, 'baz': 3, 'foo': 1}

print d
# {'baz': 3, 'foo': 1, 'bar': 2}

The documentation of pprint mentions this, but does not say why. Why the discrepancy?


pprint stands for "pretty print", also implying "pleasing to the human eye, and easily read by humans". Sorting the dict keys just follows that aim, pprint isn't supposed to be primarily fast (sorting the keys adds a penalty), but, errr, pretty. :)

print on the other hand "just prints", as fast as possible. Actually the discrepancy here is between dict's __str__ and pprint's specially crafted string conversion.


pprint had to probably implement something different from ordinary print as it's told to be pretty. Well, the output still isn't pretty, but at least sorted.

Printing dictionaries using print is most probably connected with their internal implementation (trees? hash tables?). Note that dictionaries require elements to be hashable, so this is where I'd be looking for some ordering rules. In my case, if I populate dictionary with positive integers, my output is sorted (hash(int)==int). Whatever the rule is, the print statement just travel the dictionary in most convenient and fastest way it can, and any particular order can't be assumed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜