Search code examples
pythonpython-3.xdictionarypprint

Pretty print multiple key value pairs with a specified width


I have the following structure and I want to write it into a file with specified width, and interestingly I couldn't make it work.

{'c': {' eva X': -15,
       'Cki Xi': -2,
       'I Xalt': -23,
       'Ik Xip': -8,
       'Ir 1 X': -19,
       'Xamdal': 20,
       'Xincik': 11,
       'bu aXa': -1,
       'elinde Xop': -24,
       'gol aX': 5,
       'huyu X': -6,
       'ie Xol': -14,
       'im teX': -16,
       'k Xipl': 18,
       'kriz X': 17,
       'm Xars': 7,
       'mUS aX': -13,
       'mem Xi': -21,
       'na Xog': 3,
       'ncu X ': 9,
       'ram Xo': 4,
       'tI Xat': 22,
       'vre aX': 12,
       'zay Xo': 10}}

The result should look like this, (ps: order might differ)

{'c': {"bu aXa": -1, "Cki Xi": -2, "na Xog": 3,
       "ram Xo": 4, "gol aX": 5, "huyu X": -6,
       "m Xars": 7, "Ik Xip": -8, "ncu X ": 9,
       "zay Xo": 10, "Xincik": 11, "vre aX": 12,
       "mUS aX": -13, "ie Xol": -14, " eva X": -15,
       "im teX": -16, "kriz X": 17, "k Xipl": 18,
       "Ir 1 X": -19, "Xamdal": 20, "mem Xi": -21,
       "tI Xat": 22, "I Xalt": -23, "elinde Xop": -24}}

I have tried pprint as follows but to no avail. I can't get the desired result.

import pprint

pprint.pprint(data, width=100)
pprint.pprint(data, width=200)
pprint.pprint(data, width=300)
# {'c': {' eva X': -15,
#        'Cki Xi': -2,
#        'I Xalt': -23,
#        'Ik Xip': -8,
#        'Ir 1 X': -19,
#        'Xamdal': 20...  (all of them same as above)

Solution

  • Here is the solution I have written for my own problem with slight modifications according to my needs. Still I am open to ideas. It would have been better if pprint covered this case, unfortunate.

    def prettyPrint(myDict, itemPerLine=3):
        myStr = '{'
        for k1, v1 in myDict.items():
            myStr += "'" + k1 + "': {"
            itemCount = 0
            for k2, v2 in v1.items():
                myStr += '"' + str(k2) + '": ' + str(v2) + ', '
                if itemCount == itemPerLine:
                    myStr += '\n' + ' ' * 32
                    itemCount = 0
                itemCount += 1
            myStr = myStr[:-2] + "},\n" + ' ' * 26
        return myStr[:-2] + "}"
    

    prettyPrint(data)
    {'c': {"bu aXa": -1, "Cki Xi": -2, "na Xog": 3,
           "ram Xo": 4, "gol aX": 5, "huyu X": -6,
           "m Xars": 7, "Ik Xip": -8, "ncu X ": 9,
           "zay Xo": 10, "Xincik": 11, "vre aX": 12,
           "mUS aX": -13, "ie Xol": -14, " eva X": -15,
           "im teX": -16, "kriz X": 17, "k Xipl": 18,
           "Ir 1 X": -19, "Xamdal": 20, "mem Xi": -21,
           "tI Xat": 22, "I Xalt": -23, "elinde Xop": -24}}