Readably print out a python dict() sorted by key

前端 未结 8 2190
悲&欢浪女
悲&欢浪女 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:03

    I wrote the following function to print dicts, lists, and tuples in a more readable format:

    def printplus(obj):
        """
        Pretty-prints the object passed in.
    
        """
        # Dict
        if isinstance(obj, dict):
            for k, v in sorted(obj.items()):
                print u'{0}: {1}'.format(k, v)
    
        # List or tuple            
        elif isinstance(obj, list) or isinstance(obj, tuple):
            for x in obj:
                print x
    
        # Other
        else:
            print obj
    

    Example usage in iPython:

    >>> dict_example = {'c': 1, 'b': 2, 'a': 3}
    >>> printplus(dict_example)
    a: 3
    b: 2
    c: 1
    
    >>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
    >>> printplus(tuple_example)
    (1, 2)
    (3, 4)
    (5, 6)
    (7, 8)
    

提交回复
热议问题