Python pretty print dictionary of lists, abbreviate long lists

后端 未结 5 2040
甜味超标
甜味超标 2020-12-09 11:10

I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function

5条回答
  •  [愿得一人]
    2020-12-09 12:02

    This recursive function I wrote does something you're asking for.. You can choose the indentation you want too

    def pretty(d, indent=0):
        for key in sorted(d.keys()):
            print '\t' * indent + str(key)
            if isinstance(d[key], dict):
                pretty(d[key], indent+1)
            else:
                print '\t' * (indent+1) + str(d[key])
    

    The output of your dictionary is:

    key_1
        ['EG8XYD9FVN', 'S2WARDCVAO', 'J00YCU55DP', 'R07BUIF2F7', 'VGPS1JD0UM', 'WL3TWSDP8E', 'LD8QY7DMJ3', 'J36U3Z9KOQ', 'KU2FUGYB2U', 'JF3RQ315BY']
    key_2
        ['162LO154PM', '3ROAV881V2', 'I4T79LP18J', 'WBD36EM6QL', 'DEIODVQU46', 'KWSJA5WDKQ', 'WX9SVRFO0G', '6UN63WU64G', '3Z89U7XM60', '167CYON6YN']
    

提交回复
热议问题