Readably print out a python dict() sorted by key

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

    An easy way to print the sorted contents of the dictionary, in Python 3:

    >>> dict_example = {'c': 1, 'b': 2, 'a': 3}
    >>> for key, value in sorted(dict_example.items()):
    ...   print("{} : {}".format(key, value))
    ... 
    a : 3
    b : 2
    c : 1
    

    The expression dict_example.items() returns tuples, which can then be sorted by sorted():

    >>> dict_example.items()
    dict_items([('c', 1), ('b', 2), ('a', 3)])
    >>> sorted(dict_example.items())
    [('a', 3), ('b', 2), ('c', 1)]
    

    Below is an example to pretty print the sorted contents of a Python dictionary's values.

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

提交回复
热议问题