漂亮打印具有指定宽度的多个键值对

时间:2022-02-27 10:46:57

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)

结果应如下所示(ps:顺序可能不同)

{'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.

我试过pprint如下,但无济于事。我无法得到理想的结果。

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)

3 个解决方案

#1


0  

In the documentation of pprint it says -

在pprint的文档中,它说 -

The desired output width is constrained using the width parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will be made. If compact is false (the default) each item of a long sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line.

使用width参数约束所需的输出宽度;默认值为80个字符。如果无法在约束宽度内格式化结构,则将尽最大努力。如果compact为false(默认值),则长序列中的每个项目将在单独的行上格式化。如果compact为true,则在每个输出行上将格式化适合宽度的项目。

So you can use the compact=True parameter for your desired output. But you need to find the approx width for compacting three key:value in one line like you expected.

因此,您可以使用compact = True参数来获得所需的输出。但是你需要找到压缩三个键的近似宽度:一行中的值与预期的一样。

#2


0  

Here is my suggested solution using pure Python. Comments are included in order to help understand my logic:

这是我使用纯Python建议的解决方案。包含注释是为了帮助理解我的逻辑:

indict = {'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}}

#Create a string from dict.
dictString = str(indict)

#Set the number of elements you want for each row.
elements = 3

#Split the string to individual records of dict.
dictString = dictString.split(',')

#Add ' ,' to the end.
newString = list(map(lambda i: i+" ,", dictString[:-1]))
newString.append(dictString[-1])

#Find the position of the dict 'opening' bracket in order to be used as padding point.
pos = newString[0].find(": {") + 2
print(pos)

#Form row with number of elements defined by the 'elements' variable.
newString = ["".join(newString[i:i+elements]) for i in range(0,len(newString),elements)]

#Pad each row to match with the padding point.
newString = [newString[0]] + [i.rjust(len(i) + pos,' ') for i in newString[1:]]

#Create a final string, appending all rows.
finalString = "\n".join(newString)
print(finalString)

#Write the string to file.
with open("output.txt", "w") as outFile:
       outFile.write(finalString)

Output from print(finalString):

print的输出(finalString):

{'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}}

Same goes for the file's content.

文件的内容也是如此。

#3


0  

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.

这是我为自己的问题编写的解决方案,根据我的需要稍作修改。我仍然对创意持开放态度。如果pprint覆盖了这个案子会更好,不幸的是。

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}}

#1


0  

In the documentation of pprint it says -

在pprint的文档中,它说 -

The desired output width is constrained using the width parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will be made. If compact is false (the default) each item of a long sequence will be formatted on a separate line. If compact is true, as many items as will fit within the width will be formatted on each output line.

使用width参数约束所需的输出宽度;默认值为80个字符。如果无法在约束宽度内格式化结构,则将尽最大努力。如果compact为false(默认值),则长序列中的每个项目将在单独的行上格式化。如果compact为true,则在每个输出行上将格式化适合宽度的项目。

So you can use the compact=True parameter for your desired output. But you need to find the approx width for compacting three key:value in one line like you expected.

因此,您可以使用compact = True参数来获得所需的输出。但是你需要找到压缩三个键的近似宽度:一行中的值与预期的一样。

#2


0  

Here is my suggested solution using pure Python. Comments are included in order to help understand my logic:

这是我使用纯Python建议的解决方案。包含注释是为了帮助理解我的逻辑:

indict = {'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}}

#Create a string from dict.
dictString = str(indict)

#Set the number of elements you want for each row.
elements = 3

#Split the string to individual records of dict.
dictString = dictString.split(',')

#Add ' ,' to the end.
newString = list(map(lambda i: i+" ,", dictString[:-1]))
newString.append(dictString[-1])

#Find the position of the dict 'opening' bracket in order to be used as padding point.
pos = newString[0].find(": {") + 2
print(pos)

#Form row with number of elements defined by the 'elements' variable.
newString = ["".join(newString[i:i+elements]) for i in range(0,len(newString),elements)]

#Pad each row to match with the padding point.
newString = [newString[0]] + [i.rjust(len(i) + pos,' ') for i in newString[1:]]

#Create a final string, appending all rows.
finalString = "\n".join(newString)
print(finalString)

#Write the string to file.
with open("output.txt", "w") as outFile:
       outFile.write(finalString)

Output from print(finalString):

print的输出(finalString):

{'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}}

Same goes for the file's content.

文件的内容也是如此。

#3


0  

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.

这是我为自己的问题编写的解决方案,根据我的需要稍作修改。我仍然对创意持开放态度。如果pprint覆盖了这个案子会更好,不幸的是。

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}}