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

时间:2018-06-28 10:58:09

标签: python python-3.x dictionary pprint

我具有以下结构,我想将其写入指定宽度的文件中,有趣的是我无法使其正常工作。

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

结果应如下所示((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}}

我尝试了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 个答案:

答案 0 :(得分:0)

在pprint的文档中说-

  

使用width参数来限制所需的输出宽度;默认值为80个字符。如果无法在限制的宽度内格式化结构,则将尽力而为。如果compact为false(默认设置),则长序列的每个项目都将在单独的行上格式化。如果compact为true,则将在每条输出行上格式化所有适合宽度的项目。

因此,可以将compact=True参数用于所需的输出。但是您需要找到压缩宽度的大致宽度,如您所愿,将三个key:value压缩在一行中。

答案 1 :(得分:0)

这是我建议使用纯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)

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

文件内容相同。

答案 2 :(得分:0)

这是我为自己的问题写的解决方案,根据我的需要进行了一些修改。我仍然愿意接受想法。不幸的是,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}}