打印没有换行符的字典?

Printing a dictionary without newlines?

我正试图在我的打印输出中获得正确的格式,但它比应该的更棘手。我的 objective 是在字典中读取我的代码,将其转换为列表,对其进行排序,然后将其打印回文本文件,看起来像

"String" "Float"

"String" "Float"

"String" "Float"

当它打印时

字符串

浮动

字符串

浮动

查看作为我的字典的原始数据,它看起来像:

{'blahblah\n': 0.3033367037411527, 'barfbarf\n': 0.9703779366700716, 

我怀疑 \n 换行命令与此有关。但我似乎无法减轻它。我的代码如下:

#Open the text file and read it back it
h = open('File1.txt', 'r')
my_dict = eval(h.read())

#Print out the dictionary
print "Now tidying up the data......"
z = my_dict

#Turn the dictionary into a list and print it
j = open('File2.txt', 'w')
z = z.items()
z.sort(key=lambda t:t[1])
z.reverse()
for user in z:
    print >> j, user[0], user[1]
j.close()

这段代码在我程序的几乎所有其他部分都能完美运行。出于某种原因,它在这里有问题。

\n是换行符。写入文件时显示为换行符。您应该在打印之前将其删除:

print >> j, user[0].strip(), user[1].strip()

或者更好的是,在转向列表的同时进行:

z = [item.strip() for item in z.items()]