Readably print out a python dict() sorted by key

前端 未结 8 2181
悲&欢浪女
悲&欢浪女 2020-12-04 17:19

I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improv

相关标签:
8条回答
  • 2020-12-04 18:06

    You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.

    pprint([(key, mydict[key]) for key in sorted(mydict.keys())])
    
    0 讨论(0)
  • 2020-12-04 18:09

    Actually pprint seems to sort the keys for you under python2.5

    >>> from pprint import pprint
    >>> mydict = {'a':1, 'b':2, 'c':3}
    >>> pprint(mydict)
    {'a': 1, 'b': 2, 'c': 3}
    >>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
    >>> pprint(mydict)
    {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    >>> d = dict(zip("kjihgfedcba",range(11)))
    >>> pprint(d)
    {'a': 10,
     'b': 9,
     'c': 8,
     'd': 7,
     'e': 6,
     'f': 5,
     'g': 4,
     'h': 3,
     'i': 2,
     'j': 1,
     'k': 0}
    

    But not always under python 2.4

    >>> from pprint import pprint
    >>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
    >>> pprint(mydict)
    {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
    >>> d = dict(zip("kjihgfedcba",range(11)))
    >>> pprint(d)
    {'a': 10,
     'b': 9,
     'c': 8,
     'd': 7,
     'e': 6,
     'f': 5,
     'g': 4,
     'h': 3,
     'i': 2,
     'j': 1,
     'k': 0}
    >>> 
    

    Reading the source code of pprint.py (2.5) it does sort the dictionary using

    items = object.items()
    items.sort()
    

    for multiline or this for single line

    for k, v in sorted(object.items()):
    

    before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

    So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

    Python3 Update

    Pretty print by sorted keys (lambda x: x[0]):

    for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
        print("{} : {}".format(key, value))
    

    Pretty print by sorted values (lambda x: x[1]):

    for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
        print("{} : {}".format(key, value))
    
    0 讨论(0)
提交回复
热议问题