Readably print out a python dict() sorted by key

前端 未结 8 2179
悲&欢浪女
悲&欢浪女 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())])
    

提交回复
热议问题